When a Javascript promise is fulfilled

I read the document on JavaScript promises ( https://developers.google.com/web/fundamentals/getting-started/primers/promises ) and one of the examples uses promises sequence.

// Start off with a promise that always resolves
var sequence = Promise.resolve();

// Loop through our chapter urls
story.chapterUrls.forEach(function(chapterUrl) {
  // Add these actions to the end of the sequence
  sequence = sequence.then(function() {
    return getJSON(chapterUrl);
  }).then(function(chapter) {
    addHtmlToPage(chapter.html);
  });
})

      

I was curious how this worked, since I assumed it would start executing the code when the first one. then was added to the promise sequence. When I debugged the code, the sequence of promises was not executed until the last line of code was executed in the script tags. So my question is, when do promises actually get executed? Thank you.

+3


source to share


1 answer


See this post for a good explanation of the promises execution context:



.Then () handlers are called asynchronously after the current thread of execution has finished (as the Promises / A + spec says, when the JS engine reverts to "framework code"). This is true even for promises that resolve synchronously, such as Promise.resolve (). Then (...). This is for programming consistency so that the .then () handler is sequentially called asynchronously, whether the promise is resolved immediately or later. This prevents some synchronization errors and makes it easier for the calling code to execute asynchronously all the time.

+2


source







All Articles