【发布时间】:2019-10-01 18:31:20
【问题描述】:
如果我在 JS 中执行异步操作并链接 2 个 .then 调用,当我在第一个 .then 的异步操作上使用 return 关键字时,执行会按预期进行:
- 第一个异步操作在 x 时间后执行
- 第二个异步操作在 x 时间后执行
但是,如果第一个 .then 中的异步操作没有明确使用 return,则两个操作同时完成,在初始异步操作后 x 时间量,例如:
场景 1:
function doAsync() {
return new Promise(res => {
setTimeout(() => res('hi'), 3000);
});
}
doAsync().then(() => {
console.log('async then 1'); // executes 3 seconds after
return doAsync();
}).then(() => {
console.log('async then 2'); // executes 6 seconds after
});
场景 2:
function doAsync() {
return new Promise(res => {
setTimeout(() => res('hi'), 3000);
});
}
doAsync().then(() => {
console.log('async then 1'); // executes 3 seconds after
doAsync(); // no return
}).then(() => {
console.log('async then 2'); // executes 3 seconds after
});
这是为什么? return 是否表示在继续第二个承诺之前等待第一个承诺解决?所以如果跳过返回,第二个异步操作在等待第一个承诺解决之前开始?
【问题讨论】:
-
does return signify to wait for the first promise to resolve- 不是真的......因为doAsync返回一个承诺,.then返回的承诺“采用”doAsync的值......因此直到这个承诺解决了 -
您可能需要阅读有关Promise Chaining的文档
-
或阅读promisesaplus.com的承诺解决程序
标签: javascript asynchronous promise