Search code examples
javascriptes6-promise

When Does a JavaScript Promise Execute


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

// 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 it worked, since I assumed it would start executing the code when the first .then was added to the promise sequence. When I debugged the code, the promise sequence wasn't executed until the last line of code had been executed within the script tags. So my question is when do promises actually get executed?


Solution

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

    All .then() handlers are called asynchronously after the current thread of execution finishes (as the Promises/A+ spec says, when the JS engine returns back to "platform code"). This is true even for promises that are resolved synchronously such as Promise.resolve().then(...). This is done for programming consistency so that a .then() handler is consistently called asynchronously no matter whether the promise is resolved immediately or later. This prevents some timing bugs and makes it easier for the calling code to see consistent asynchronous execution.