我正在阅读有关JavaScript承诺的文档(https://developers.google.com/web/fundamentals/getting-started/primers/promises),其中一个示例使用了一系列承诺。何时执行Javascript承诺
// 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添加到承诺序列时开始执行代码。当我调试代码时,只有在脚本标记中执行了最后一行代码之后,才会执行承诺序列。所以我的问题是什么时候承诺实际上被执行?谢谢。
是您编写完整脚本的脚本吗?因为那么很明显,那么它就会在所有事情之后出现。 –
检查此:https://stackoverflow.com/questions/36870467/what-is-the-order-of-execution-in-javascript-promises –