在Array#map()中异步/等待 [英] Async/Await inside Array#map()
问题描述
此代码出现编译时错误:
const someFunction = async (myArray) => {
return myArray.map(myValue => {
return {
id: "my_id",
myValue: await service.getByValue(myValue);
}
});
};
错误消息是:
await是保留字
为什么我不能像这样使用它?
我也尝试了另一种方法,但是它给了我同样的错误:
const someFunction = async (myArray) => {
return myArray.map(myValue => {
const myNewValue = await service.getByValue(myValue);
return {
id: "my_id",
myValue: myNewValue
}
});
};
您不能像您想象的那样执行此操作,因为如果await
不是直接在async
函数内部,则不能使用. >
在这里要做的明智的事情是使传递给map
的函数异步.这意味着map
将返回一个promise数组.然后,当所有的诺言都返回时,我们可以使用Promise.all
获得结果.当Promise.all
本身返回一个promise时,外部函数不必是async
.
const someFunction = (myArray) => {
const promises = myArray.map(async (myValue) => {
return {
id: "my_id",
myValue: await service.getByValue(myValue)
}
});
return Promise.all(promises);
}
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);
}
这篇关于在Array#map()中异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!