场景:想对遍历一个数组,循环发起请求,并且是在请求结果返回后才能发起下一个请求.
刚开始我想的是用forEach来遍历的,后来发现forEach不会等到请求结果返回.
init() {
const arr = ['a', 'b', 'c', 'd'];
arr.forEach(async (el) => {
let res = await new Promise((resolve, reject) => {
let time = el === 'c' ? 5000 : 1000;
setTimeout(() => {
resolve(el)
}, time)
})
console.log(res, 'init')
})
}
原因是forEach里已经封装了一层,
我的理解是forEach是遍历执行了
async (el) => {
let res = await new Promise((resolve, reject) => {
let time = el === 'c' ? 5000 : 1000;
setTimeout(() => {
resolve(el)
}, time)
})
console.log(res, 'init')
}
这一段代码,那就很好理解了,我执行了多个async异步任务,异步任务里面执行await同步
解决方法:
使用for of 对数组进行循环调用
async init() {
const arr = ['a', 'b', 'c', 'd'];
for (let [index, value] of arr.entries()) {
let res = await new Promise((resolve, reject) => {
let time = value === 'c' ? 5000 : 1000;
setTimeout(() => {
resolve(value)
}, time)
})
console.log(res, 'init')
}
}