[英]javascript nodejs promise all gets executed later
I have multiple promises like this: 我有多个这样的承诺:
module.exports = function (a, b, c) {
return someAsync(() => {
someFunc(a);
})
.then(() => myPromises(a, b, c))
.then(result => {
console.log('log the result: ', JSON.stringify(result)); // empty
})
};
const myPromises = function myPromises(a, b, c){
Promise.all([
somePromise(a),
someOtherPromise(b)
]).then(function (data) {
Promise.all([
anotherPromise(data[0]),
yetanotherPromise(data[1])
]).then(function (finalResult) {
console.log('check out finalResult: ', JSON.stringify(finalResult)); // i see the expected results here
return finalResult;
}).catch(err => { return err });
}).catch(err => { return err });
};
why is the console.log('log the result: ', JSON.stringify(result));
为什么
console.log('log the result: ', JSON.stringify(result));
returning empty? 返回空? in other words, why is this line getting executed before the
promise.all
is finished? 换句话说,为什么在
promise.all
完成之前执行此行? how can I make it to wait for promise all and then execute? 我该如何使其等待所有承诺然后执行?
Not sure which promise you want to return, but the general idea would be to return the Promise.all there, instead of just calling Promise.all. 不确定要返回哪个承诺,但通常的想法是在此处返回Promise.all,而不是仅调用Promise.all。
const myPromises = function myPromises(a, b, c){
return Promise.all([
The problem is your second promise.all isn't returning anything for it to pass to the main Promise.all Try this edited piece of code 问题是您的第二个承诺.all不会返回任何内容以传递给主Promise.all尝试这段经过编辑的代码
module.exports = function (a, b, c) {
return someAsync(() => {
someFunc(a);
})
.then(() => myPromises(a, b, c))
.then(result => {
console.log('log the result: ', JSON.stringify(result)); // empty
})
};
const myPromises = function myPromises(a, b, c){
return Promise.all([ //missing return
somePromise(a),
someOtherPromise(b)
]).then(function (data) { //data from first promise all
return Promise.all([ //missing return: passes data to next then
anotherPromise(data[0]),
yetanotherPromise(data[1])
])
})
.then(function (finalResult) { //data from second promise all
console.log('check out finalResult:',JSON.stringify(finalResult)); // i see the expected results here
return finalResult; //passes data to next then or top level return whichever available
})
.catch(err => { return err }); // top level catch works for the entire chain
};
The reason for your code not working is that promise chain is single flow, you didn't return anything from second promise for it to pass it to the outer promise.all chain 您的代码无法正常工作的原因是承诺链是单流的,您没有从第二个承诺返回任何东西来将其传递给外部承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.