awaitasyncfor循环中的使⽤有⼀需求需要给数组中每⼀项赋值,我这么写的
async mounted() {
let list = await this.setArr();
console.log(list, 'list')
},
methods: {
setArr() {
let arr = [{id: 1, groupList: []}, {b:1, groupList: []}];
arr.forEach(async item => {
console.upList, 'upList')
});
console.log(arr, 'arr')
return arr;
},
fetchGroupList(id){
return new Promise(resolve => {
setTimeout(() => {
let groupList = [{groupId: 1, name: 1}, {groupId: 2, name: 2}];
resolve(groupList);
}, 1000)
})
}
}
打印信息如下:
会先执⾏console.log(arr, 'arr')⽽不是等待forEach中await执⾏完,setArr⽅法更改如下写法:
methods: {
async setArr() {
let arr = [{id: 1, groupList: []}, {b:1, groupList: []}];
const peomiseArr = arr.map(async item => {
console.upList, 'upList')
});
await Promise.all(peomiseArr);
console.log(arr, 'arr')
return arr;
},
fetchGroupList(id){
return new Promise(resolve => {
setTimeout(() => {
let groupList = [{groupId: 1, name: 1}, {groupId: 2, name: 2}];
resolve(groupList);
}, 1000)
})
}
}
打印结果:
但是promise.all是⼀次发出所有请求,等到所有请求返回后,按照接收结果的顺序打印出upList;最后同事推荐另外⼀种写法,串⾏发送请求:
methods: {
async setArr() {
let arr = [{id: 1, groupList: []}, {b:1, groupList: []}];
for(let [idx, item] ies()) {
console.upList, idx, 'upList')
await和async使用方法}
console.log(arr, 'arr')
return arr;
},
fetchGroupList(id){
return new Promise(resolve => {
setTimeout(() => {
let groupList = [{groupId: 1, name: 1}, {groupId: 2, name: 2}];
resolve(groupList);
}, 1000)
})
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论