Use async await with Array.map

JavascriptTypescriptPromiseAsync AwaitEcmascript 2017

Javascript Problem Overview


Given the following code:

var arr = [1,2,3,4,5];

var results: number[] = await arr.map(async (item): Promise<number> => {
        await callAsynchronousOperation(item);
        return item + 1;
    });

which produces the following error:

> TS2322: Type 'Promise<number>[]' is not assignable to type 'number[]'. > Type 'Promise<number> is not assignable to type 'number'.

How can I fix it? How can I make async await and Array.map work together?

Javascript Solutions


Solution 1 - Javascript

The problem here is that you are trying to await an array of promises rather than a Promise. This doesn't do what you expect.

When the object passed to await is not a Promise, await simply returns the value as-is immediately instead of trying to resolve it. So since you passed await an array (of Promise objects) here instead of a Promise, the value returned by await is simply that array, which is of type Promise<number>[].

What you probably want to do is call Promise.all on the array returned by map in order to convert it to a single Promise before awaiting it.

According to the MDN docs for Promise.all:

> The Promise.all(iterable) method returns a promise that resolves > when all of the promises in the iterable argument have resolved, or > rejects with the reason of the first passed promise that rejects.

So in your case:

var arr = [1, 2, 3, 4, 5];

var results: number[] = await Promise.all(arr.map(async (item): Promise<number> => {
    await callAsynchronousOperation(item);
	return item + 1;
}));

This will resolve the specific error you are encountering here.

Depending on exactly what it is you're trying to do you may also consider using Promise.allSettled, Promise.any, or Promise.race instead of Promise.all, though in most situations (almost certainly including this one) Promise.all will be the one you want.

Solution 2 - Javascript

Solution below to properly use async await and Array.map together. Process all elements of the array in parallel, asynchronously AND preserve the order:

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const randomDelay = () => new Promise(resolve => setTimeout(resolve, Math.random() * 1000));

const calc = async n => {
  await randomDelay();
  return n * 2;
};

const asyncFunc = async () => {
  const unresolvedPromises = arr.map(n => calc(n));
  const results = await Promise.all(unresolvedPromises);
};

asyncFunc();

Also codepen.

Notice we only "await" for Promise.all. We call calc without "await" multiple times, and we collect an array of unresolved promises right away. Then Promise.all waits for resolution of all of them and returns an array with the resolved values in order.

Solution 3 - Javascript

There's another solution for it if you are not using native Promises but Bluebird.

You could also try using Promise.map(), mixing the array.map and Promise.all

In you case:

  var arr = [1,2,3,4,5];

  var results: number[] = await Promise.map(arr, async (item): Promise<number> => {
    await callAsynchronousOperation(item);
    return item + 1;
  });

Solution 4 - Javascript

If you map to an array of Promises, you can then resolve them all to an array of numbers. See Promise.all.

Solution 5 - Javascript

You can use:

for await (let resolvedPromise of arrayOfPromises) {
  console.log(resolvedPromise)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

If you wish to use Promise.all() instead you can go for Promise.allSettled() So you can have better control over rejected promises.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

Solution 6 - Javascript

This is simplest way to do it.

await Promise.all(
    arr.map(async (element) => {
        ....
    })
)

Solution 7 - Javascript

I'd recommend using Promise.all as mentioned above, but if you really feel like avoiding that approach, you can do a for or any other loop:

const arr = [1,2,3,4,5];
let resultingArr = [];
for (let i in arr){
  await callAsynchronousOperation(i);
  resultingArr.push(i + 1)
}

FYI: If you want to iterate over items of an array, rather than indices (@ralfoide 's comment), use of instead of in inside let i in arr statement.

Solution 8 - Javascript

A solution using modern-async's map():

import { map } from 'modern-async'

...
const result = await map(myArray, async (v) => {
    ...
})

The advantage of using that library is that you can control the concurrency using mapLimit() or mapSeries().

Solution 9 - Javascript

I had a task on BE side to find all entities from a repo, and to add a new property url and to return to controller layer. This is how I achieved it (thanks to Ajedi32's response):

async findAll(): Promise<ImageResponse[]> {
    const images = await this.imageRepository.find(); // This is an array of type Image (DB entity)
    const host = this.request.get('host');
    const mappedImages = await Promise.all(images.map(image => ({...image, url: `http://${host}/images/${image.id}`}))); // This is an array of type Object
    return plainToClass(ImageResponse, mappedImages); // Result is an array of type ImageResponse
  }

Note: Image (entity) doesn't have property url, but ImageResponse - has

Solution 10 - Javascript

This might help someone.

const APISimulator = (v) => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve({ data: v });
    }, v * 100);
});

const arr = [7, 6, 5, 1, 2, 3];

const res = () => arr.reduce(async (memo, v, i) => {
    const results = await memo;
    console.log(`proccessing item-${i + 1} :`, v)
    await APISimulator(v);
    console.log(`completed proccessing-${i + 1} :`, v)

    return [...results, v];
}, []);

res().then(proccessed => console.log(proccessed))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlonView Question on Stackoverflow
Solution 1 - JavascriptAjedi32View Answer on Stackoverflow
Solution 2 - JavascriptMikiView Answer on Stackoverflow
Solution 3 - JavascriptGabriel CheungView Answer on Stackoverflow
Solution 4 - JavascriptDan BeaulieuView Answer on Stackoverflow
Solution 5 - JavascriptAbhijeet NarvekarView Answer on Stackoverflow
Solution 6 - JavascriptAjit A. KenjaleView Answer on Stackoverflow
Solution 7 - JavascriptBecksterView Answer on Stackoverflow
Solution 8 - Javascriptnicolas-vanView Answer on Stackoverflow
Solution 9 - JavascriptVictor MuresanuView Answer on Stackoverflow
Solution 10 - JavascriptKiran PoojaryView Answer on Stackoverflow