如何解决在JavaScript中,处理程序将按什么顺序执行?
给我的印象是then
处理函数按其添加顺序进行处理。
例如,如果您运行以下代码:
function getResolvedPromise(result) {
return new Promise((resolve,reject) => {
console.log(`Promise executor,result will be ${result}`);
resolve(result);
});
}
function logThen(label,result) {
console.log(`[${label}] Promise then,result = ${result}`);
return result;
}
// Shows that then handlers get run in the order they are added.
const prom1 = getResolvedPromise("prom1");
const prom2 = getResolvedPromise("prom2");
prom2.then(logThen.bind(null,"1"));
prom2.then(logThen.bind(null,"2"));
prom2.then(logThen.bind(null,"3"));
prom1.then(logThen.bind(null,"4"));
prom1.then(logThen.bind(null,"5"));
prom1.then(logThen.bind(null,"6"));
这就是要记录的内容。这对我来说很有意义。
Promise executor,result will be prom1
Promise executor,result will be prom2
[1] Promise then,result = prom2
[2] Promise then,result = prom2
[3] Promise then,result = prom2
[4] Promise then,result = prom1
[5] Promise then,result = prom1
[6] Promise then,result = prom1
但是,如果运行此命令:
// Order of execution is interleaved when then handlers are directly attached?
const prom1 = getResolvedPromise("prom1")
.then(logThen.bind(null,"1"))
.then(logThen.bind(null,"2"))
.then(logThen.bind(null,"3"));
const prom2 = getResolvedPromise("prom2")
.then(logThen.bind(null,"4"))
.then(logThen.bind(null,"5"))
.then(logThen.bind(null,"6"));
这就是要记录的内容。
Promise executor,result = prom1
[4] Promise then,result = prom2
什么解释了这种交错行为?
请注意,规范包含一些相关信息here。具体来说,它是关于HostEnqueuePromiseJob的:
作业必须以与安排它们的HostEnqueuePromiseJob调用相同的顺序运行。
如果我们查看specification for Promise.prototype.then
,我们会看到它调用了HostEnqueuePromiseJob。因此,这对我来说唯一有意义的方法是按交错顺序调用then
调用。但是...我真的不知道怎么回事,因为我发布的两个代码示例似乎与我等效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。