async和await

180 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

async await是用于声明异步函数的。 async 用于修饰函数,await只能在带了async的函数内使用。

一. 使用方法

const func = async function() {
    console.log(123);
    const a = await new Promise((resolve) => {
        resolve(2);
    }) 
    console.log(a);
    console.log(3);
}
func();

执行结果:

image.png

我们通常用这种方法去改变promise的执行顺序,等得到promise的执行结果之后再执行下面的同步代码。

二. 返回值

1. async函数的返回

开头我们说了async用来修饰函数,让函数变成一个异步函数。 image.png

他的返回值也是一个promise,所以这个函数的执行返回是可以用promise的then()和catch()方法的。

(async function() {
    return 123; 
})().then(res => {console.log(res)})  // 123

(async function() {
    return new Promise(resolve => resolve(123)) 
})().then(res => {console.log(res)})   // 123

2. 被await的promise的返回结果

await就是为了等待promise执行结果后才执行函数内后面代码的。

当如果被等待的promise,resolve了一个结果后,我们将会正常开始执行函数后面的代码。

(async function() {
    const a = await new Promise(resolve => resolve(123)) 
    console.log(a);
    console.log(456);
})()
// 123
// 456

当被等待的promise,reject了一个错后,将会报错并不再执行后面的代码。

(async function() {
    const a = await new Promise((resolve,reject) => reject(123) ) 
    console.log(a);
    console.log(456);
})()

执行结果:

image.png

那么当没有结果呢

(async function() {
    const a = await new Promise((resolve,reject) => {return 123} ) 
    console.log(a);
    console.log(456);
})()

结果什么都没有打印,这说明如果promise没有结果,那么await之后的语句也不再执行。

3.如何处理错误

通过上面reject的例子可以发现如果被等待的promise报错,会阻碍下面代码的执行,所以我们有必要处理这些错误,让成功和错误后都能有相应的代码能处理这个结果,那我们就可以用try去处理这个promise,如下例,我们模拟出错的情况处理错误:

(async function() {
    try {
        const a = await new Promise((resolve,reject) => reject(123)) 
        console.log("我成功了!")
    } catch(err) {
        console.log('我出错了,但我不想管!', err);
    }
    console.log(456);

})()

执行结果: image.png

三. 有关面试题

其实这个博客是我看到有人问了一个题后想写的,暂时也没想到太多的题,就贴一下那个题吧,后面想到合适的题,再贴过来。

function log(time){
    setTimeout(function(){
        console.log(time);
        return 1;
    },time)
}
async function funccc(){
    let a = await log(1000);
    let b = await log(3000);
    let c = log(2000);
    console.log(a);
    console.log(1)
}
funccc();

这个题里面的await就是来误导的,在await后面不是一个promise的时候,是不会去等待其执行完成的. 所以其实这个问题就很简单,前面介个setTimeout存入队列,先执行,a,1,这个时候,a已经定义,但是没有初始值,所以就是undefined,执行完后,再执行队列中的值,也是不会相互等待哦,依次执行下来,就是1000,2000,3000。