繁体   English   中英

如何等待所有promise在forEach循环中添加到数组?

[英]How to wait for all promises being added to array in forEach loop?

我希望我的函数返回诺言数组。 函数内部的代码是异步的。 我需要检查每个元素的类型并进行一些处理。 我不知道该函数如何返回所有的诺言-一旦完成异步处理。 的jsfiddle

function addFeatures (input) {

  var result = [];
  input.forEach(function (el) {

    if (Number.isInteger(el)) {
      // placeholder asynchronous
      setTimeout(function () {
        result.push(
          new Promise(function (resolve, reject) {
            resolve(el.toString() + 'string')
          })
        )
      }, 2000);
    } 
    else {
      // placeholder synchronous
      result.push(
        new Promise(function (resolve, reject) {
          resolve(el + 'string')
        }));
    }
  })
  return result;
};

var arr = [1, 'text']
var final = addFeatures(arr)
// should log 2 promises but logs only 1 - the synchronous
console.log(final)

最重要的是要立即创建的承诺,做它里面的东西异步:

function addFeatures (input) {
  var result = [];
  input.forEach(function (el) {
    result.push(new Promise(function (resolve, reject) {
      if (Number.isInteger(el)) {
        // placeholder asynchronous
        setTimeout(function () {
          resolve(el.toString() + 'string')
        }, 2000);
      } else {
        // placeholder synchronous
        resolve(el + 'string')
      }
    });
  });
  return result;
}

我还建议使用map而不是forEach + push

基于贝尔吉的出色回答,这是我的贡献:

1-函数addFeaturesarray.map

function addFeatures (input) {
    return input.map(function(el) {
        return new Promise(function (resolve, reject) {
            if (Number.isInteger(el)) {
                setTimeout(resolve, 2000, el.toString() + 'string');
                /* setTimeout(reject, 2000, el.toString() + 'string'); //for reject */
            }
            else {
                resolve(el + 'string');
                /* reject(el + 'string'); //for reject */
            }
        })
    });
};

2-测试addFeatures结果的addFeatures

如果您不能正确地管理以上代码的答案, 有时 asynchronous placeholder promiseresolve将变为pending并返回undefined 这就是为什么您需要Promise.all的原因:

function foo(){
    return Promise.all(addFeatures([1, 'text'])).then(values => {
        return values;
    }, function() {
        throw 'Promise Rejected';
    });
}

3-在上面调用您的函数

foo().then(function(result) {
    console.log("result => " + result);
}).catch(function(error) {
    console.log("error => " + error);
});

小提琴

暂无
暂无

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

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