当前位置:网站首页>js,for循环内callback异步转换成同步执行
js,for循环内callback异步转换成同步执行
2022-07-24 16:28:00 【胖若西瓜】
如果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 < 5; 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 < 5; index++) {
const element = array[index];
try {
let res = await get(element)
console.log(res)
} catch (error) {
console.log(error)
return
}
}
console.log('循环完毕')
}
down()
// 正确
// 正确
// 正确
// 正确
// 错误
边栏推荐
猜你喜欢

Envi5.3 open GF-1 WFV data

Princeton calculus reader 02 Chapter 1 -- composition of functions, odd and even functions, function images

TCP protocol debugging tool tcpengine v1.3.0 tutorial

Yolov6 trains its own data set

Quickly view the version of redis in the server

Some understanding of the rank sum of matrix and the rank of image

Talk about C pointer

About SQL data query statements

ArcGIS layer annotation display

Yolov4 trains its own data set
随机推荐
Unity 相机自由移动控制
LaneATT
Multithreading (basic)
2019q1 global smartphone shipments: Huawei vivo increased significantly, while Apple plummeted 30.2%!
Wentai technology and Baoxin software deepened 5g cooperation, and 5g manufacturing settled in Baowu, China
What is the difference between cookies, localstorage and sessionstorage?
ArcGIS layer annotation display
Enter a URL to this page to show it. What happened in this process?
栈与队列——1047. 删除字符串中的所有相邻重复项
hping3安装使用
Princeton calculus reader 02 Chapter 1 -- composition of functions, odd and even functions, function images
Yolov3 trains its own data set
124 maximum path sum in binary tree
【技术】uniapp 之 在线选座 demo
Stack and queue - 1047. Delete all adjacent duplicates in the string
'resultmap'must match' (constructor?, id*, result*, association*, collect problem solving
My first blog
What does Baidu promote "delete and recall" mean?
【技术】uniapp之聊天室 demo
QT keyboard event (II) -- long press the key to trigger the event event repeatedly, and the problem is solved