异步迭代数组然后返回数组?

时间:2017-07-06 00:50:46

标签: javascript arrays node.js

我试图异步迭代数组,然后想要将值从被调用的函数推送到新数组。

我有以下代码,但不知道如何处理这个......

let companies = [];
_.forEach(notProcessed, function(company) {
    companies.push(processThem(company));
});
return companies;

当然,在打印/退回公司时,我会收到一个空数组。

提前致谢,感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

一种方法:

var notProcessed = ['a', 'b', 'c'];

function processThem(company) {
  // Example long process
  return new Promise((resolve) => {
    setTimeout(() => resolve(company), 500);
  });
}

function processArrayAsync(notProcessed) {
  var companies = [];
  var promise = Promise.resolve();
  for(let next of notProcessed) {
    promise = promise
      .then(() => processThem(next))
      .then(company => companies.push(company));
  }

  return promise.then(() => companies);
}

processArrayAsync(notProcessed).then(console.log);

在es6 async函数中使用new有更好的方法

var notProcessed = ['a', 'b', 'c'];

async function processThem(company) {
  // Example long process
  return new Promise((resolve) => {
    setTimeout(() => resolve(company), 500);
  });
}

async function processArrayAsync(notProcessed) {
  var companies = [];
  for(let next of notProcessed) {
    let res = await processThem(next);
    companies.push(res);
  }
  return companies;
}

processArrayAsync(notProcessed).then(console.log);

我真的很喜欢这种处理异步操作的第二种方式:)