先来一个小例子看一下 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
})();
注意:
- await 必须放在 async 的函数内才能生效,否则会报错
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
- 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");
答案是