异步代码同步执行的await用法

一,普通的包含异步的函数

function test(){
    console.log("111")
    setTimeout(()=>{
        console.log("222")
    },1000)
    console.log("333")
}
test()

实现的效果:
在这里插入图片描述

二,使用promise改写成同步

function timeOut(){
    return new Promise((resolve)=>{
         setTimeout(()=>{
            console.log("222")
            resolve()
        },1000)
    })
   
}
async function test(){
    console.log("111")
   await timeOut()
    console.log("333")
}
test()

结果:

> 111
> 222
> 333

三,多层await

function timeOut(){
    return new Promise((resolve)=>{
         setTimeout(()=>{
            console.log("222")
            resolve()
        },1000)
    })
   
}
async function test(){
    console.log("111")
   await timeOut()
    console.log("333")
}
function test2(){
    console.log("0000")
   test()
    console.log("4444")
}
test2()

因为test2中的test里面虽然有await,但是test2中却没有,而test里有异步,所以会先执行同步代码,先000,再111,就直接到444了。

> 0000
> 111
> 4444
> 222
> 333

三,多层await,同步需要使用await

function timeOut(){
    return new Promise((resolve)=>{
         setTimeout(()=>{
            console.log("222")
            resolve()
        },1000)
    })
   
}
async function test(){
    console.log("111")
   await timeOut()
    console.log("333")
}
async function test2(){
    console.log("0000")
  await test()
    console.log("4444")
}
test2()

这里主要就是把test2中的异步也是用await来处理了,因为其内部还是用了await,await返回是个resolve的promise对象,所以这里的await也是生效的。
也就是说await只会把该作用域下的异步代码转化为同步,如果外层还是需要同步执行,则还需要一个await

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值