javascript - 如何从javascript中array.map中的异步函数返回一个值?
问题描述
如何从 array.map 中的异步函数返回值我试图从它们访问值但我得到 Array [[object Promise], [object Promise], [object Promise], [object Promise]]
?
我想在里面异步,array1.map
因为我有一些需要时间的过程,所以我需要使用等待。
var array1 = [1, 4, 9, 16];
// pass a function to map
const test = async ()=>{
const map1 = await array1.map(async x => 'hi');
return map1;
// expected output: Array [2, 8, 18, 32]
}
test().then((data)=>{
console.log(data)
})
预期输出:排列['hi', 'hi', 'hi', 'hi']
我的输出:[[object Promise], [object Promise], [object Promise], [object Promise]]
解决方案
您需要使用Promise.all
函数,在其中放置一系列承诺
var array1 = [1, 4, 9, 16];
// pass a function to map
const test = async () => {
const map1 = await Promise.all(array1.map(async x => 'hi'));
return map1;
}
test().then((data) => {
console.log(data)
});
预期输出:数组 ['hi', 'hi', 'hi', 'hi']
推荐阅读
- c++ - 为什么 strcat 到 getenv() 会更改后续的 getenv() 调用?
- c++ - 静态 volatile 变量的动态初始化何时发生?
- javascript - 知道绿点的坐标,使用输入在红点周围滚动
- matlab - 通过叉积将矢量旋转 90 度
- java - Nginx:如何从外部请求反向代理到特定的本地主机 url
- python - 从 HTML 文件中的 Python 脚本调用 Python 函数
- java - 使用 Java 时如何在 Spanner 中实现分页
- javascript - SAPUI5 - 在输入字段上设置焦点时如何在 android 上禁用软键盘
- makefile - 在 Makefile 目标中使用标志
- flutter - 为什么列表是绑定的?