我正在阅读一份关于JavaScript Promise的文档(https://developers.google.com/web/fundamentals/getting-started/primers/promises),其中一个例子使用了Promise序列。
// 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);
});
})
我很好奇它是如何工作的,因为我认为当第一个.then被添加到promise序列中时,它会开始执行代码。 当我调试代码时,promise序列要等到脚本标签内的最后一行代码执行完毕才会执行。那么我的问题是,什么时候才实际执行promises?谢谢。