gpt4 book ai didi

javascript - 什么时候检查 ES6 promise 履行处理程序表?

转载 作者:行者123 更新时间:2023-11-30 19:01:26 24 4
gpt4 key购买 nike

下面的 resolve() 函数和 then() 函数是 ES6 Promise 机制中唯一查看并添加实现处理程序的函数吗?作业队列(并将它们标记为已添加且不再添加)?

let promise = new Promise(function(resolve, reject) {
console.log("resolve, reject are", resolve, reject);
setTimeout(function() {
resolve("this is the success data");
}, 1000);
});

promise.then(
function(a) {
console.log("Success.", a);
promise.then(function(a) { console.log("Go have a drink.", a); });
},
function(a) {
console.log("failure", a)
}
);

上述代码的替代方法是,resolve() 直接完成,而不是在 setTimeout() 中。 then(fn) 是否会将 fn 添加到此 promise 的履行处理程序表(而非作业队列)中,或者如果 promise 已经解决,直接将fn添加到job queue,fn标记为“已经添加到job queue”,不需要再次添加?

另一方面,resolve() 是 JS ES6 提供的函数,它将 promise 标记为“已解决”(状态),并检查此 promise 的履行处理程序表是否为空或不。如果有这样的处理程序(并且之前不应该被标记为已添加到作业队列),则将这些处理程序添加到作业队列并标记为已添加。

并且无论如何,假设 fulfillment handler 表中有 fn1, fn2, fn3, ... 等,每一个作为 fn1(resolvedValue) 添加到作业队列中,其中 resolvedValueresolve(resolveValue) 调用在内部记住?

并且根本没有访问 fulfillment handler 表的其他情况。作业队列作业由 JS 事件循环执行,因此当所有 GUI“单击事件处理程序”等完成后,作业队列中的履行(和拒绝)处理程序将被执行,然后是 setTimeout 和 setInterval处理程序也被执行?这就是履行处理程序表和作业队列的工作方式吗?

最佳答案

Is it true that the resolve() function and then() function below are the only functions in the ES6 Promise mechanism that look at and add the fulfillment handlers to the job queue?

是的。 (reject 还会查看表并删除处理程序而不将它们添加到作业队列中)。

Is it true that the then(fn) will add the fn to the fulfillment handler table (not job queue) for this promise, or if the promise has already been resolved, directly add the fn to the job queue?

是的。

and the fn is marked as "already added to job queue" and no need to be added again?

不,fn 根本没有标记。它可以多次传递给 then,在这种情况下它需要运行多次。
但是,是的,当 promise 履行并安排回调作业时,履行处理程序表将被清除。

And in any event, suppose there are fn1, fn2, fn3, ... etc in the fulfillment handler table, each one is added to the job queue as fn1(resolvedValue), where the resolvedValue is remembered internally by the resolve(resolveValue) call?

是的。虽然技术上resolve does not always fulfill the promise .

And there are no other situation where the fulfillment handler table is accessed at all.

是的。我想知道你为什么关心。

The job queue jobs are executed by the JS event loop, so that when all the GUI "click event handlers", etc are done, then the fulfillment (and rejection) handlers in the job queue are executed, and then also the setTimeout and setInterval handlers are also executed? Is this how the fulfillment handler table and job queue work?

是的。但是请注意 click handlers, setTimeout and setInterval have a separate event queue from promise jobs .

关于javascript - 什么时候检查 ES6 promise 履行处理程序表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59476887/

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