gpt4 book ai didi

javascript - 在评估 Promise.all 的结果时使用没有超时值的 setTimeout

转载 作者:行者123 更新时间:2023-12-01 01:39:34 26 4
gpt4 key购买 nike

Promise.all MDN docs包含评估多个 Promise.all 结果的示例,但在没有超时值的 setTimeout 函数中。

来自文档:

// this will be counted as if the iterable passed is empty, so it gets fulfilled
var p = Promise.all([1,2,3]);
// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled
var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected
var p3 = Promise.all([1,2,3, Promise.reject(555)]);

// using setTimeout we can execute code after the stack is empty
setTimeout(function() {
console.log(p);
console.log(p2);
console.log(p3);
});

// logs
// Promise { <state>: "fulfilled", <value>: Array[3] }
// Promise { <state>: "fulfilled", <value>: Array[4] }
// Promise { <state>: "rejected", <reason>: 555 }

有人可以用比代码中的注释更多的文字来解释一下它实现了什么吗?

最佳答案

setTimeout没有延迟值的调用只是将传入的函数放入队列中以由 the JavaScript event loop 执行。这通常是下一个时钟周期,尽管队列中可能还有其他已安排的事情,因此该函数将在这些事情之后。

通过将 Promise 解析放入队列中,可以类似地安排它。这意味着 setTimeout 将在 promise 完成后立即安排函数完成。反过来,这意味着 pp2p3 的值将在 JavaScript 事件循环的当前运行中处于待处理状态,然后当调用延迟了 setTimeout 的函数时,处于最终状态。

演示程序流程:

//console.logs from Stack Overflow snippets don't print the state of the promise
//you can open the browser developer tools and click the button to run the snippet
//in order to see that output

var p = Promise.all([1,2,3]); //<-- a pending promise is created
p.finally(() => console.log("promise fulfilled", p));

console.log("this call is executed immediately", p); //<-- the same run of the event loop

setTimeout(function() {
console.log("this call is scheduled to execute in the future", p); //<-- to be executed in a subsequent run of the loop.
});

关于javascript - 在评估 Promise.all 的结果时使用没有超时值的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52543879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com