101

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?

4
  • 1
    I don't think you can have async arrow functions. Commented Feb 27, 2017 at 15:49
  • Relevant github.com/tc39/ecmascript-asyncawait/issues/7 Commented Feb 27, 2017 at 15:51
  • 1
    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. Commented Feb 27, 2017 at 15:55
  • async/await is part of ES2017 (this year's release), not ES7 (last year's release). Commented Mar 1, 2017 at 14:34

6 Answers 6

217

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

9 Comments

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.
|
84

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.

Comments

18

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

4 Comments

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.
13

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

let results = array.map((e) => fetch('....'))
results  = await Promise.all(results)

1 Comment

+1 for breaking down into two instructions. one-liners are neat and all, but sometimes they're overly lengthy and unreadable
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://stackoverflow.com/a/64978715/8339172 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.

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.