本文介绍了在评估Promise.all结果时使用没有超时值的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

包含一个示例,该示例评估多个 Promise.all 结果,但在 setTimeout 函数中,而没有

The Promise.all MDN docs contain an example of evaluating multiple Promise.all results, but within a setTimeout function without a timeout value.

来自文档:

// 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 }

有人可以帮助解释一下实现了什么,比代码中的注释多了几句话?

Can someone help explain what this achieves, with a few more words than the comment in the code?

推荐答案

只是将传入的函数放在要由。通常这是下一个刻度,尽管队列中可能已经安排了其他事项,所以该功能将排在这些之后。

setTimeout called with no delay value just puts the passed in function on the queue to be executed by the JavaScript event loop. That is usually the next tick, although there could be other things on the queue already scheduled, so the function will be after those.

承诺解决方案通过将其放在队列中而得到类似的安排。这意味着 setTimeout 将在完成承诺之后 立即安排功能完成。反过来,这意味着 p p2 p3 将在当前的JavaScript事件循环运行中挂起,然后在最终状态下调用 setTimeout 延迟的函数。

Promise resolution gets scheduled similarly by putting it on the queue. That means setTimeout will schedule the function completion immediately after the promises are finalized. In turn, this means that the value of p, p2, and p3 will be pending in the current run of the JavaScript event loop, then in the final state when the function delayed by setTimeout is called.

演示程序的流程:

//console.logs from StackOverflow 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.
});

这篇关于在评估Promise.all结果时使用没有超时值的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 12:29