带有异步等待的数组归约功能

时间:2018-10-05 22:36:16

标签: javascript async-await

我试图基于异步运算符从数组对象中跳过一个对象。我已经尝试过以下情况,但遇到类型错误。

尝试方法1

newObjectArray = await Promise.all(objectAray.reduce(async (result, el) => {
  const asyncResult = await someAsyncTask(el);
  if (asyncResult) {
      result.push(newSavedFile);
  }
  return result;
}, []));

尝试方法2

newObjectArray = await Promise.all(objectAray.reduce(async (prevPromise, el) => {
  const collection = await prevPromise;
  const asyncResult = await someAsyncTask(el);
  if (asyncResult) {
      prevPromise.push(newSavedFile);
  }

  collection.push(newSavedFile);
  return collection;
}, Promise.resolve([])));

错误

'TypeError: #<Promise> is not iterable',
'    at Function.all (<anonymous>)',

1 个答案:

答案 0 :(得分:0)

在第一次尝试中,result是一个诺言,因为所有async函数在被调用时都会评估为一个诺言,因此必须await result才能推入数组,然后您不需要Promise.all:

 newObjectArray = await objectAray.reduce(async (result, el) => {
  const asyncResult = await someAsyncTask(el);
  if (asyncResult) {
    (await result).push(newSavedFile);
  }
  return result;
}, []);

但我猜想随后进行过滤会更快:

 newObjectArray = (await Promise.all(objArray.map(someAsyncTask))).filter(el => el);