我试图为数组中的所有水果设置随机数,并返回一个包含减速器中具有异步函数的所有水果的对象,但只返回数组的最后一个元素
(async () =>
console.log(
await [("apple", "banana", "orange")].reduce(async (o, fruit) => {
const random_number = await new Promise((resolve) => setTimeout(() => resolve(Math.random()), 200));
return { ...o, [fruit]: random_number };
}, {})
))();Run Code Online (Sandbox Code Playgroud)
你们非常接近。主要问题是您将数组写为而[(...)]不是[...]. 在您的代码中,该数组仅包含一个值,如果删除它,()您将拥有三个值。有关详细信息,请参阅逗号运算符。
你必须考虑的另一件事是async函数总是返回一个承诺,所以你await o也必须 -
(async () =>
console.log(
await ["apple", "banana", "orange"].reduce(async (o, fruit) => {
const rand = new Promise((resolve) => setTimeout(() => resolve(Math.random()), 200))
return { ...await o, [fruit]: await rand }
}, {})
))();Run Code Online (Sandbox Code Playgroud)
{
"apple": 0.8731611352383968,
"banana": 0.163521266739585,
"orange": 0.8419246752641664
}
Run Code Online (Sandbox Code Playgroud)
上面使用的注释reduce将按系列(顺序)解决承诺。其他评论建议map->Promise.all将并行(同时)解决承诺
| 归档时间: |
|
| 查看次数: |
756 次 |
| 最近记录: |