我有一个包含在函数中的承诺。我将使用不同的输入参数多次调用该函数。每次承诺解决时,我都会将解决的值推送到存储数组中。
当我所有的调用承诺都得到解决后,我将在其他函数中使用这个存储数组。
是否有任何干净的方法可以在不使用“全局”变量的情况下进行设置?
下面的代码是我能想到的实现这项工作的唯一方法:
// Set global-ish variables that can be referenced from multiple functions
var storageArray = [];
var numberOfPromiseCalls = 10;
var promiseCallsCount = 0;
// Setup promise wrapper
function promiseWrapper(inputParams){
return new Promise(function(resolve, reject) {
// awesome stuff at work here using inputParams
resolve(desiredOutput);
}
})
// call promise 10 times
for(i=0;i<numberOfPromiseCalls;i++){
// actual promise call
promiseWrapper(inputParams[i]).then(function (desiredOutput) {
// push resolve to storage array
storageArray.push(desiredOutput);
// test if this resolve is the "last" resolve of all the promises we called
promiseCallsCount++;
if(promiseCallsCount == numberOfPromiseCalls){
// ************************
// call a function that can work with the final storageArray
// ************************
}
})
}
我的意思是,上面的代码可以工作,但是感觉很丑。有很多不明确的地方,你必须跟踪可变的层次结构。有更好的方法吗?
我建议你使用Promise.all
通过一系列的承诺。调用then
当所有承诺都得到解决时,将让您处理所有响应。
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
for (i=0;i<numberOfPromiseCalls;i++){
storageArray.push(promiseWrapper(inputParams[i]));
}
Promise.all(storageArray).then(responses => {
// responses is an array of all promises responses
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)