js async and await

本文解释了async和await关键字在JavaScript中的作用,强调了async函数不会阻塞代码并返回Promise,以及await必须在async函数中使用以等待Promise结果。通过例子展示了它们在函数调用顺序上的影响。
摘要由CSDN通过智能技术生成

async 用于修饰函数,不会阻塞代码,且将返回数据时自动封装为promise

await 必须要在 async 函数内使用,阻塞取返回值,如返回值非Promise 则返回该值本身,如果是 Promise 则获取 Promise 的值

 function time (){
        console.log(2)
        return new Promise(resolve => {
            setTimeout(function (){
                console.log("time-end")
                return resolve("time")
            }, 6000)
        })
    }
    async function test1(){
        console.log(1);
        const time1 = await  time() //打印顺序 1256789 time-end 34
        // const time1 = time() //打印顺序 123456789 time-end 
        console.log(3, time1);
        console.log(4);
        return "test1"
    }
    console.log(5, test1())
    console.log(6)
    console.log(7)
    console.log(8)
    console.log(9)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值