async/await inside arrow functions (Array#map/filter)
Asked Answered
E

6

94

I'm getting compile time error in 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?

Enyedy answered 27/2, 2017 at 15:46 Comment(4)
I don't think you can have async arrow functions.Fantoccini
Relevant github.com/tc39/ecmascript-asyncawait/issues/7Charybdis
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.Charybdis
async/await is part of ES2017 (this year's release), not ES7 (last year's release).Kentkenta
A
208

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);
}
Abate answered 27/2, 2017 at 23:1 Comment(9)
in this case array of promises is not slower that classic for let in array ?Sielen
@Sielen Probably, but the difference will be inconsequential next to service.getByValue, which may well involve a network call...Abate
thanks I've start using it, anyway readibility is better than velocity, because most of ES6 async techniques always will be slower, but who careSielen
@Abate Can this handle errors or throttling/delays between calls?Johnathon
@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.Abate
Good note would be to specify you need to put await in front of Promise.all, but here since is directly returned it's not needed since return does await for you.Nitro
@Joan Albert You certainly do not need to put await in. In fact you can't as the function is not asynchronous. Promise.all simply returns a promise, which can just be returned like any JavaScript object.Abate
@Abate yes, you're right, if you want to have all the array promises solved, you would need to add the async like ... = async (myArray) => ...Nitro
@Joan Albert but then the function will return a Promise, as all asynchronous functions do...Abate
R
80

If you want to run map with an asynchronous mapping function you can use the following code:

const resultArray = await Promise.all(inputArray.map(async (i) => someAsyncFunction(i)));

How it works:

  • inputArray.map(async ...) returns an array of promises - one for each value in inputArray.
  • Putting Promise.all() around the array of promises converts it into a single promise.
  • The single promise from Promise.all() returns an array of values - the individual promises each resolve to one value.
  • We put await in front of Promise.all() so that we wait for the combined promise to resolve and store the array of resolved sub-promises into the variable resultArray.

In the end we get one output value in resultArray for each item in inputArray, mapped through the function someAsyncFunction. We have to wait for all async functions to resolve before the result is available.

Rock answered 8/10, 2019 at 4:56 Comment(0)
B
17

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

Burkhardt answered 27/2, 2017 at 15:57 Comment(4)
thanks, upvoted, but your code return array with empty objects (i.e. [{}, {}]). I think I need to include somewhere await, but couldn't realize whereEnyedy
What does the service.getByValue function look like?Burkhardt
it just returns ES6 PromiseEnyedy
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.Teece
E
10

it will be 2 instructions, but just shift "await" with the extra instruction

let results = array.map((e) => fetch('....'))
results  = await Promise.all(results)
Embryogeny answered 7/7, 2021 at 4:21 Comment(0)
D
1

I tried all these answers but no one works for my case because all answers return a promise object not the result of the promise like this:

{
  [[Prototype]]: Promise
  [[PromiseState]]: "fulfilled"
  [[PromiseResult]]: Array(3)
  0: ...an object data here...
  1: ...an object data here...
  2: ...an object data here...
  length: 3
  [[Prototype]]: Array(0)
}

Then I found this answer https://mcmap.net/q/225245/-async-await-map-not-awaiting-async-function-to-complete-inside-map-function-before-mapping-next-item that states if map function is not async or promise aware. So instead of using await inside map function, I use for loop and await the individual item because he said that for loop is async aware and will pause the loop.

Daze answered 27/9, 2021 at 6:8 Comment(0)
L
0

When you want each remapped value resolved before moving on to the next, you can process the array as an asynchronous iterable.

Below, we use library iter-ops, to remap each value into promise, and then produce an object with resolved value, because map itself shouldn't be handling any promises internally.

import {pipe, map, wait, toAsync} from 'iter-ops';

const i = pipe(
    toAsync(myArray), // make asynchronous
    map(myValue => {
        return service.getByValue(myValue).then(a => ({id: 'my_id', myValue: a}))
    }),
    wait() // wait for each promise
);

(async function() {
    for await (const a of i) {
        console.log(a); // print resulting objects
    }
})

After each value, we use wait to resolve each remapped value as it is generated, to keep resolution requirement consistent with the original question.

Lyon answered 25/12, 2021 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.