javascriptasync-awaitecmascript-2017

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


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?


Solution

  • 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);
    }