【问题标题】:Order of execution for PromisesPromise 的执行顺序
【发布时间】:2020-03-13 20:15:30
【问题描述】:

我正在阅读 this documentation 关于 Promise,我有些不明白。

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

wait().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1);

有这个例子输出1 2 3 4

所以,1 先打印是正常的,但为什么是2 3 是下一个而不是4? 它们都在 then() 内,4setTimeout 内,但它没有作为参数传递的毫秒数。

【问题讨论】:

  • 简短的回答是,Promise.resolve().then(() => console.log(2)).then(() => console.log(3)); 实际上在 setTimeout 之前执行,因为它在所谓的“微任务队列”而不是“回调队列”中执行。
  • 关于“它没有作为参数传递的毫秒数”。当您在setTimeout 函数中未指定 ms 或将其设置为 0 时,它实际上具有默认最小值,每个浏览器都不同
  • @Konrud 真的吗?它有最小值吗?
  • 是的,超时限制为 ≥ 4 毫秒。欲了解更多信息,请阅读:developer.mozilla.org/en-US/docs/Web/API/…(在此标题下Reasons for delays longer than specified
  • 令人着迷。但是,我认为您提供的链接中有一些额外的条件:如果我没看错的话,它只会在一定数量的 settimeout 排队后将其限制为 4ms。 calls are throttled to a minimum of once every 4 ms when successive calls are triggered due to callback nesting (where the nesting level is at least a certain depth), or after certain number of successive intervals.

标签: javascript asynchronous promise timeout


【解决方案1】:

setTimeout 是全部原因。试试这个对比:

const wait2 = ms => new Promise(resolve => resolve());

wait2().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1);

wait 函数在没有超时的情况下解析。这符合你的预期,1423

即使您没有将数字传递给setTimeout,javascript 解释器也会等到处理队列被清除后再运行setTimeout 的内容

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    相关资源
    最近更新 更多