【发布时间】: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() 内,4 在 setTimeout 内,但它没有作为参数传递的毫秒数。
【问题讨论】:
-
简短的回答是,
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