我试图基于异步运算符从数组对象中跳过一个对象。我已经尝试过以下情况,但遇到类型错误。
尝试方法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>)',
答案 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);