本文介绍了一切承诺解决后退货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面有一个代码示例,我希望在所有承诺都解决之后,从 main函数返回baz变量。
Having a code sample below, I'd like to get baz variable returned from 'main' function after all promises resolved.
exports.foo = function(bar) {
var baz;
// some kind of promises are here forming array of promises p
// some of promises may change the baz variable
Promise.all(p).then(() => {
// returning expression for main function is here
// return baz here // does not work
});
// return baz //cannot be done because it would be earlier than all the async promises are resolved
}
推荐答案
在主要返回值之后承诺解决,因此返回一个baz的承诺:
Promises resolve after main returns, so return a promise of baz instead:
exports.foo = function(bar) {
var baz;
return Promise.all(p).then(() => baz);
}
exports.foo(3).then(baz => console.log(baz)).catch(e => console.error(e));
这篇关于一切承诺解决后退货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!