[英]Is there a way to guarantee `Promise.all` resolves after the `then` chain of an inner promise?
有没有办法保证Promise.all
在内部承诺的then
链之后解决?
例:
const promiseOne = new Promise((resolve, reject) => {
setTimeout(function(){
console.log('promiseOne after 1 second')
resolve()
}, 1000)
}).then(()=> {
setTimeout(function(){
console.log('promiseOne then chain, after 2 seconds')
}, 1000)
})
Promise.all([promiseOne])
.then(() => {
console.log('Promise.all then chain after 1 second')
})
日志:
promiseOne after 1 second
Promise.all then chain after 1 second
promiseOne then chain, after 2 seconds
then
s以正确的顺序运行,但是第一个只是设置超时,因此console.log
s的运行顺序与then
相反。 如果要等待该超时运行,然后再继续执行链,则需要使用从中返回的其他promise, then
:
const promiseOne = new Promise((resolve, reject) => { setTimeout(function(){ console.log('promiseOne after 1 second') resolve() }, 1000) }).then(() => new Promise((resolve, reject) => { setTimeout(function(){ console.log('promiseOne then chain, after 2 seconds') resolve() }, 1000) }) ) Promise.all([promiseOne]) .then(() => { console.log('Promise.all then chain after 1 second') })
最简单的方法是传递您已经在做的最后一个then
返回的承诺。 如果您将控制台日志从setTimeout
取出, then
从setTimeout
取出,则将看到它以所需的顺序执行。
它按该顺序记录的原因是因为setTimeout
是异步的。
尝试这样:
const promiseOne = new Promise((resolve, reject) => {
setTimeout(function(){
console.log('promiseOne after 1 second')
resolve()
}, 1000)
}).then(()=> new Promise(resolve => {
setTimeout(function(){
console.log('promiseOne then chain, after 2 seconds')
resolve()
}, 1000)
})
有了第一个then
返回一个承诺,它将一直等到您的setTimeout
并以正确的顺序继续。
编辑:作为奖励,使用setTimeout
,此帮助器超级有用:
const wait = ms => () => new Promise(resolve => setTimeout(resolve,ms));
您可以这样使用:
Promise.resolve()
.then(wait(2000))
.then(() => {
doSomething();
})
您必须在内部承诺的当时链中返回一个新的承诺:
const promiseOne = new Promise((resolve, reject) => { setTimeout(function(){ console.log('promiseOne after 1 second') resolve(); }, 1000) }).then(()=> { return new Promise((resolve, reject) => { setTimeout(function(){ console.log('promiseOne then chain, after 2 seconds'); resolve(); }, 1000) }); }) Promise.all([promiseOne]) .then(() => { console.log('Promise.all then chain after 1 second') })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.