简体   繁体   English

如何在诺言中处理这种情况?

[英]How to handle such case in promises?

I have an array where each element will go through 2 nested async tasks if some conditions hold. 我有一个数组,如果某些条件成立,每个元素将通过2个嵌套的异步任务。 Otherwise, will go through 1 normal sync task and when all done return the array with the new updates. 否则,将执行1个正常的同步任务,并在完成所有任务后返回带有新更新的阵列。

Here is a simplified version of my code: 这是我的代码的简化版本:

    someFunction(array) {
    array.forEach((element, index) => {
      if (some checks hold) {
        asyncTask1(element).then(updatedElement => {
          asyncTask2(updatedElement).then(elementFinal => {
            array[index] = elementFinal;
          });
        });
        return;
      }
      array[index] = normalSyncTask(element);
    });
  }

I need this function to return the updated array only when all elements are processed: 我仅在处理所有元素时才需要此函数返回更新后的数组:

someFunction(array).then(updatedArray => { // Do something with the updated array });

This was my attempt: 这是我的尝试:

someFunction(array) {
    var promises = [];
    array.forEach((element, index) => {
      if (some checks hold) {
        var promise = asyncTask1(element);
        promise.then(updatedElement => {
          asyncTask2(updatedElement).then(elementFinal => {
            array[index] = elementFinal;
          });
        });
        promises.push(promise);
        return;
      }
      array[index] = normalSyncTask(element);
    });
    return Promise.all(promises).then(() => Promise.resolve(array));
  }

Excuse my stupid attempt but I cannot really get a good grasp of how promises exactly work no matter how many tutorials I read. 请原谅我的愚蠢尝试,但是无论我阅读了多少教程,我都无法真正理解诺言如何正确发挥作用。

This should work: 这应该工作:

someFunction(array){
    const promises = array.map((element, index) => {
        if(some checks hold){
            return asyncTask1(element).then(asyncTask2);
        }
        return normalSyncTask(element);
    });

    return Promise.all(promises).then((values) => {
        console.log('Everything is OK', values);
    });
}

You generate an array of promises using Array.map and wait for all of them to be resolved using Promise.all . 您可以使用Array.map生成一个Array.map数组,并等待使用Promise.all解决所有这些Promise.all

The values that are not a promise will be ignored by Promise.all and be returned with the promises results in the values array returned by the function. 不是Promise.all的值将被Promise.all忽略,并与Promise.all结果一起返回到函数返回的values数组中。

Your was very close with your attempt 您的尝试非常亲密

function someFunction(array) {
    var promises = [];
    array.forEach((element, index) => {
        if (some checks hold) {
            // push Promise from last async function
            promises.push(asyncTask1(element).then(updatedElement => {
                return asyncTask2(updatedElement).then(elementFinal => {
                    array[index] = elementFinal;
                });
            }));
            return;
        }
        array[index] = normalSyncTask(element);
    });
    return Promise.all(promises).then(() => array);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM