I'm trying to skip one object from an array objects based on a async operator. I've tried following cases, but getting a Type error.
Tried Method 1
newObjectArray = await Promise.all(objectAray.reduce(async (result, el) => {
const asyncResult = await someAsyncTask(el);
if (asyncResult) {
result.push(newSavedFile);
}
return result;
}, []));
Tried Method 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([])));
Error
'TypeError: #<Promise> is not iterable',
' at Function.all (<anonymous>)',
I'm trying to skip one object from an array objects based on a async operator. I've tried following cases, but getting a Type error.
Tried Method 1
newObjectArray = await Promise.all(objectAray.reduce(async (result, el) => {
const asyncResult = await someAsyncTask(el);
if (asyncResult) {
result.push(newSavedFile);
}
return result;
}, []));
Tried Method 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([])));
Error
'TypeError: #<Promise> is not iterable',
' at Function.all (<anonymous>)',
Share
Improve this question
asked Oct 5, 2018 at 22:36
Ankit BalyanAnkit Balyan
1,32919 silver badges33 bronze badges
1
- Could you please explain what is the desired output? – gr4viton Commented Oct 5, 2018 at 22:39
1 Answer
Reset to default 15In your first try, result
is a promise as all async
functions evaluate to a promise when called, so you have to await result
before you can push to the array, and then you don't need the Promise.all:
newObjectArray = await objectAray.reduce(async (result, el) => {
const asyncResult = await someAsyncTask(el);
if (asyncResult) {
(await result).push(newSavedFile);
}
return result;
}, []);
But I'd guess that it is way faster to just filter afterwards:
newObjectArray = (await Promise.all(objArray.map(someAsyncTask))).filter(el => el);