对没有全局变量的多个事件使用promise回调 [英] Using promise callbacks for multiple events without global variables

查看:326
本文介绍了对没有全局变量的多个事件使用promise回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数包含的承诺。我将使用不同的输入参数多次调用此函数。每次promise都解析后,我将解析后的值推送到存储数组中。

I have a promise wrapped in a function. I will call this function multiple times using different input parameters. Each time the promise resolves I push the resolved value into a storage array.

当我所有的被叫Promise都已解决后,我将在其他函数中使用这个存储数组。

When all my called promises have resolved I will then use this storage array in other functions.

如果有任何干净的方法来设置它而不使用global-ish变量?

If there any clean way to set this up without using "global-ish" variables?

以下代码是我能想到的唯一方法:

The code below is the only way I can think of to make this work:

// 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
      // ************************

    }
  })
}

我的意思是,上面的代码有效,但男人觉得很难看。存在很多歧义,你需要跟踪变量层次结构。有没有更好的方法呢?

I mean, the code above works, but man it feels ugly. There's a lot of ambiguity going on and variable hierarchy's you have to keep track of. Is there any better way of doing this?

推荐答案

我建议您使用 Promise.all 传递一系列承诺。调用然后将允许您在所有承诺得到解决后处理所有响应。

I would suggest you using of Promise.all with passing an array of your promises. Invoking then will let you to handle all response when all of the promises are resolved.

参考: 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
});

这篇关于对没有全局变量的多个事件使用promise回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆