关于vue.js:map遍历数组时正确使用async与await

9次阅读

共计 479 个字符,预计需要花费 2 分钟才能阅读完成。

1. 开发环境 vue
2. 电脑系统 windows10 专业版
3. 在开发的过程中, 咱们常常会解决一些数据, 须要拿到一个 xxx 在去申请另外一个接口, 然而数据是异步操作, 所以赋值的时候始终是空, 上面我来分享一下。
4. 废话不多说, 间接上效果图:

5. 上面我来分享

// 残缺代码
this.list = this.list.map(async (item) => {let a = await this.$Cmethods.getfilesimg(item.fileKey);
    item.img = a[0];
    return item;
});
this.list = await Promise.all(this.list);

6. 剖析与解决

1. 别离打印 item 和 this.list, 发现 item 外面有值, 然而 this.list 外面没有, 狐疑是异步
2. 因为 async 函数返回的是一个 Promise, 所以 map 返回的是 Promise 数组. 必须等到所以 Promise 失去解决之后再进行赋值
3. 通过 await Promise.all(xxx);// 解决 

7. 本期的分享到了这里就完结啦, 心愿对你有所帮忙, 让咱们一起致力走向巅峰。

正文完
 0