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);
}
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)
}
});
};
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
来源:https://stackoverflow.com/questions/42489918/async-await-inside-arraymap