Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对没有全局变量的多个事件使用promise回调_Javascript_Promise - Fatal编程技术网

Javascript 对没有全局变量的多个事件使用promise回调

Javascript 对没有全局变量的多个事件使用promise回调,javascript,promise,Javascript,Promise,我有一个包含在函数中的承诺。我将使用不同的输入参数多次调用此函数。每次promise解析时,我都将解析的值推送到存储阵列中 当我所有被调用的承诺都解决后,我将在其他函数中使用此存储阵列 如果没有任何干净的方法来设置它而不使用“全局ish”变量 下面的代码是我能想到的使此工作正常的唯一方法: // Set global-ish variables that can be referenced from multiple functions var storageArray = []; var nu

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

当我所有被调用的承诺都解决后,我将在其他函数中使用此存储阵列

如果没有任何干净的方法来设置它而不使用“全局ish”变量

下面的代码是我能想到的使此工作正常的唯一方法:

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

    }
  })
}
//设置可从多个函数引用的全局ish变量
var-storageArray=[];
var NumberOfPromiseCall=10;
var promiseCallsCount=0;
//安装承诺包装器
函数promiseWrapper(inputParams){
返回新承诺(功能(解决、拒绝){
//使用inputParams在这里工作的很棒的东西
决定(期望输出);
}
})
//给承诺打10次电话

对于(i=0;i我建议您使用of
Promise.all
传递承诺数组。调用
然后
将允许您在解决所有承诺时处理所有响应

参考:

(i=0;i)的
{
//响应是所有承诺响应的数组
});

你是如何在这里获得解析范围的-
storageArray.push(resolve);
??@McRist抱歉我的错误。翻译成伪代码后,我没有理解。它现在被编辑。“我有一个承诺,我会多次打电话给你”-无法调用承诺,它是一个结果值。它不能多次解析。你的意思是你有一个返回承诺的函数吗?@Bergi是的,这就是我的意思,我将编辑问题以反映这一点
for (i=0;i<numberOfPromiseCalls;i++){
  storageArray.push(promiseWrapper(inputParams[i]));
}

Promise.all(storageArray).then(responses => {
  // responses is an array of all promises responses
});