5

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>)',
1
  • Could you please explain what is the desired output? Commented Oct 5, 2018 at 22:39

1 Answer 1

15

In 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);
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't filter will cost on double iteration over the array.
@ankit yup bat that might cost you a few nanoseconds, while executing one someAsyncTask after another will take you much more. Just put a Date.now() before and after this, and see how both perform ...
thanks for your answer. Its not possible to use Promise.all() when I reduce to Object. So I love your answer which helped that purpose :) thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.