Async/Await inside Array#map()

async/await array#map
async push to array
async.map example
await within array map
await array of promises
js async await in array map
async await fetch array
promise.all async await

I'm getting compile time error with this code:

const someFunction = async (myArray) => {
    return myArray.map(myValue => {
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue);
        }
    });
};

Error message is:

await is a reserved word

Why can't I use it like this?

I also tried another way, but it gives me same error:

 const someFunction = async (myArray) => {
    return myArray.map(myValue => {
        const myNewValue = await service.getByValue(myValue);
        return {
            id: "my_id",
            myValue: myNewValue 
        }
    });
};

You can't do this as you imagine, because you can't use await if it is not directly inside an async function.

The sensible thing to do here would be to make the function passed to map asynchronous. This means that map would return an array of promises. We can then use Promise.all to get the result when all the promises return. As Promise.all itself returns a promise, the outer function does not need to be async.

const someFunction = (myArray) => {
    const promises = myArray.map(async (myValue) => {
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue)
        }
    });
    return Promise.all(promises);
}

How to use Async and Await with Array.prototype.map(), MDN Web Docs: The map() method creates a new array with the results of calling a provided function on every element in the calling array. Today  Remember, we must wrap any code that calls await in an async function. See the promises article for more on promises, and the async/await guide. Download my free JavaScript Beginner's Handbook, and check out my upcoming Full-Stack JavaScript Bootcamp! A 4-months online training program. Signups open on May 25 2020.

That's because the function in map isn't async, so you can't have await in it's return statement. It compiles with this modification:

const someFunction = async (myArray) => {
    return myArray.map(async (myValue) => { // <-- note the `async` on this line
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue)
        }
    });
};

Try it out in Babel REPL

So… it's not possible to give recommendation without seeing the rest of your app, but depending on what are you trying to do, either make the inner function asynchronous or try to come up with some different architecture for this block.

Update: we might get top-level await one day: https://github.com/MylesBorins/proposal-top-level-await

Array.map() + async/await, So in your case: 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  Basically, I had an Array of objects upon which I had to make several calculations. One of these calculations involved making a call to an API which, of course, is asynchronous. Before my refactoring, I had no problem with using async/await inside my for..of loop. However, after making the switch to Array.map, I realized it wouldn’t be as simple.

Use async await with Array.map, Rauch in his article about async functions. Let's start with the Array#map() method: async function getUsers (userIds) { const users = userIds.map(  This is probably due to Array.map() not being implemented as a Promise. Is there a Promise-based version of Array.map? This is question differs from How to return the response from an asynchronous call, because it's about How to return batched responses wrapped inside Array.map.

Making array iteration easy when using async/await, MDN Web Docs: The map() method creates a new array with the results of calling a provided function on every element in the calling array. Today  An approach to perform async actions in array.map() is to return a promise for each item which then resolve outside the map function. Because map won’t wait for the promise to resolve, it’ll return a pending promise.

Array.map() + async/await - Estefanía García Gallardo, Return Promises in map and wait for the results. 5 mins. This article is part of a series on Asynchronous array functions in Javascript. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. NodeJS - Using Async/Await inside Array.map with 'if

Node.js, 25, 18 0 Comment. In brief, in this tutorial we will demonstrate how to use the Async/Await JavaScript feature. await Promise.all(array.map(async (item) => {. I was writing some API code recently using Node 8, and came across a place where I needed to use Array.prototype.map with an async function on each item. Async/Await is one of my favorite new…

Comments
  • I don't think you can have async arrow functions.
  • Relevant github.com/tc39/ecmascript-asyncawait/issues/7
  • To summarize from the linked github discussion, you can't do that because the anonymous function you're passing as a callback is not async and the inner await can't affect the outer function.
  • async/await is part of ES2017 (this year's release), not ES7 (last year's release).
  • in this case array of promises is not slower that classic for let in array ?
  • @stackdave Probably, but the difference will be inconsequential next to service.getByValue, which may well involve a network call...
  • thanks I've start using it, anyway readibility is better than velocity, because most of ES6 async techniques always will be slower, but who care
  • @lonesomeday Can this handle errors or throttling/delays between calls?
  • @KylePennell Yes. You'd need to handle errors either with a try..catch in the async function or with a catch handler before returning from the outer function. A throttle could be introduced before the return in the async function.
  • thanks, upvoted, but your code return array with empty objects (i.e. [{}, {}]). I think I need to include somewhere await, but couldn't realize where
  • What does the service.getByValue function look like?
  • it just returns ES6 Promise
  • It looks to me like the OP expects an array of id'ed objects as the final result, so in keeping with that I think you probably want return await Promise.all(myArray.map... for equivalency.