如果for循环内有异步方法,则不会等待异步执行完毕,就执行后面的代码,如下:
//callback => Promise
function get(element){
//模拟异步请求
setTimeout(()=>{
if(element==5){
console.log('错误')
return '错误'
}else{
console.log('正确')
return '正确'
}
},100)
}
function down(){
let array=[1,2,3,4,5,6]
for (let index = 0; index < array.length; index++) {
const element = array[index];
get(element)
}
console.log('循环完毕')
}
down()
// 循环完毕
// 正确
// 正确
// 正确
// 正确
// 错误
// 正确
假如要实现等待异步执行完毕再执行后面的代码,也就是异步转同步,如果是用callback实现的异步,则需要把callback转换成Promise,代码如下:
function get(element){
return new Promise((resolve,reject)=>{
//模拟异步请求
setTimeout(()=>{
if(element==5){
reject('错误')
}else{
resolve('正确')
}
},500)
})
}
async function down(){
let array=[1,2,3,4,5,6]
for (let index = 0; index < array.length; index++) {
const element = array[index];
try {
let res = await get(element)
console.log(res)
} catch (error) {
console.log(error)
return //遇到错误,直接跳出down方法
}
}
console.log('循环完毕')
}
down()
// 正确
// 正确
// 正确
// 正确
// 错误