js map遍历与promise一起使用会出现的问题,怎么解决?

async /await 与 Primise的关系

async/await是Promise的语法糖
所以这里我会直接使用async/await替换Promise

let result = await func()
// => 等价于
func().then(result => {
    
    
  // code here
})

// ======

async function func () {
    
    
  return 1  
}
// => 等价与
function func () {
    
    
  return new Promise(resolve => resolve(1))
}

map

map可以说是对Promise最友好的一个函数了。
我们都知道,map接收两个参数:

1、 对每项元素执行的回调,回调结果的返回值将作为该数组中相应下标的元素
2、一个可选的回调函数this指向的参数

日常工作中会有这么个场景
在这里插入图片描述
在这里插入图片描述
这是map的一般使用场景,但是当我们的一些计算操作变为异步的:比如某个参数需要请求额外接口才能获得
在这里插入图片描述
在这里插入图片描述
这时候返回的就是由Promise组成的数组了

所以为什么会说map函数为最友好的了,Promise有个函数是Promise.all对不对,它会将由Promise组成的数组依次执行,并返回一个Promise对象,这时候结果集就出来了
在这里插入图片描述
在这里插入图片描述
用Promise.all包装整个数组,然后await 获取最终结果
最后附上代码:

let list = [];
let array = [{
    
     path: "1" }, {
    
     path: "2" }, {
    
     path: "3" }];
list = await Promise.all(
  array.map(async (item) => {
    
    
    return {
    
    
      ...item,
      y_path: await this.getImage(item.path)
    };
  })
);

原文链接:

https://www.cnblogs.com/mica/p/15577084.html

一起学习,加油鸭!
拜拜

猜你喜欢

转载自blog.csdn.net/qq_33235680/article/details/128922951