Async和Await

什么是async和await?


async 定义异步函数
返回值是promise对象
当调用异步函数时,函数返回值会被resolve处理
出错也会被捕获到
异步函数内部可以使用await


await 暂停异步函数的执行
当使用在promise 前面是,await等待promise完成,并返回promise的结果
await只能写在async函数里面,
await只能和promise一起使用,不能和callback一起使用
await关键字后面可以跟任意表达式 如果是promise对象,会等promise执行完在执行下面的代码
 

async和await的使用

为了解决 promise 中的.then 链 也就是回调地狱

原始写法

function test(n) {
    return new Promise(resolve => {
        setTimeout(() => resolve(n + 100), n);
    });
}

function set1(n) {
    console.log(`set1 with ${n}`);
    return test(n);
}

function set2(n) {
    console.log(`set2 with ${n}`);
    return test(n);
}

function set3(n) {
    console.log(`set3 with ${n}`);
    return test(n);
}

promise写法

function test() {
    console.log(111);
    const time1 = 100;
    set1(time1)
        .then(time2 => set2(time2))
        .then(time3 => set3(time3))
        .then(result => {
            console.log(222);
            console.log(333);
    });
}

test();

async/await写法

async function test() {
    console.log(111);
    const time1 = 100;
    const time2 = await set1(time1);
    const time3 = await set2(time2);
    const result = await set3(time3);
    console.log(222);
    console.log(333);
}

test();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值