ES6 async + await 的使用

先来一个小例子看一下 async 的使用

async异步加载图片写法
// async 加载图片
(async function () {
    try{
        const img = await loadImg('图片地址')
        document.body.appendChild(img)
    }catch(err){
        console.log(err);
    }
})();

但 async function 最终得到的还是Promise对象,通过打印可知

const res = async function(){return 10}
console.log(res()) //Promise对象

但配上 await 之后就又变回值了

async function fn (){return 10}
(async function(){
    const result = await fn()
    console.log(result) //10 
})();

注意:

  1. await 必须放在 async 的函数内才能生效,否则会报错Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
  2. await 后面所有的代码都是异步的
async function fn1 (){
    console.log('fn1 start');
    await fn2()
    console.log('fn1 end');  //最后
}
async function fn2(){
    console.log('this is fn2');
}

console.log('start');
fn1()
console.log('end');

结果如下:

在这里插入图片描述

再复杂一点

async function fn1() {console.log("fn1 start")
    await fn2();
    console.log("fn1 end"); // 异步
    await fn3();
    console. log("fn3 end"); // 异步之后再异步
}
async function fn2() {console.log("fn2");}
async function fn3() {console.log("fn3");}

console.log("start");
fn1();
console. log("end");

答案是

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值