【问题标题】:When Does a Javascript Promise ExecuteJavascript Promise 何时执行
【发布时间】: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 序列时开始执行代码。当我调试代码时,直到在脚本标签中执行了最后一行代码后,才会执行承诺序列。所以我的问题是承诺何时真正执行?谢谢。

【问题讨论】:

标签: javascript es6-promise


【解决方案1】:

请参阅 this post 以获得对 Promise 执行上下文的详细说明:

所有 .then() 处理程序在当前执行线程完成后被异步调用(正如 Promises/A+ 规范所说,当 JS 引擎返回“平台代码”时)。即使对于像 Promise.resolve().then(...) 这样同步解决的 Promise 也是如此。这样做是为了编程的一致性,因此无论 promise 是立即解决还是稍后解决,都会一致地异步调用 .then() 处理程序。这可以防止一些计时错误,并使调用代码更容易看到一致的异步执行。

【讨论】:

  • “如果一个 promise 已经被解析,.then() 回调函数会在调用时立即执行。” 这不是真的。 Promise.resolve().then(() => console.log(1)); console.log(2);
  • @Ryan 你是对的(我的误解)。我做了更多的研究,并更新了我的答案。
  • @FrankerZ 这正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
相关资源
最近更新 更多