【发布时间】:2017-12-05 21:46:03
【问题描述】:
我正在阅读有关 javascript 承诺 (https://developers.google.com/web/fundamentals/getting-started/primers/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);
});
})
我很好奇它是如何工作的,因为我假设它会在第一个 .then 添加到 promise 序列时开始执行代码。当我调试代码时,直到在脚本标签中执行了最后一行代码后,才会执行承诺序列。所以我的问题是承诺何时真正执行?谢谢。
【问题讨论】:
-
你写的脚本是完整的脚本吗?因为 then 很明显 .then 最终会执行,因为它存在于所有内容之后。