NodeJS 09_Promise async和await

nodejs文档:https://nodejs.dev/en/learn

 创建异步函数fn,调用时不会立刻返回结果,需要then来读取

function fn() {
    return Promise.resolve(10)
}

fn().then(r => {
    console.log(r);
})

通过async可以快速的创建异步函数

异步函数的返回值可以自动封装到一个Promise中返回,此时result读取到的是一个Promise

async function fn2() {
    return 10
}

let result = fn2()
console.log(result);

使用then来读取10

async function fn2() {
    return 10
}

fn2().then(r => {
    console.log(r)
})

在saync声明的异步函数中可以使用await关键字来调用异步函数 

之前调用(Promise解决了异步调用中回调函数问题,但是多了之后不太好)

function sum(a, b) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(a + b)
        }, 2000)
    })
}

async function fn3() {
    sum(123, 456)
        .then(r => sum(r, 7))
        .then(r => sum(r, 8))
        .then(r => console.log(r))
}

想以同步的方式调用异步函数

当我们通过await去调用异步函数时,它会暂停代码的运行,直到异步代码执行有结果时,才会将结果返回

await阻塞的只是异步函数内部的代码,不会影响外部

通过await调用异步代码时,需要通过try-catch处理异常

注:await只能用于 async声明的异步函数中,或es模块的顶级作用域中

function sum(a, b) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(a + b)
        }, 2000)
    })
}

async function fn3() {
    try {
        let result = await sum(123, 456);
        result = await sum(result, 8);
        result = await sum(result, 9);
        console.log(result);    
    } catch (e) {
        console.log("出错了");
    }
}

fn3()

如果async声明的函数中没有写await,那么它里面的代码依次执行

async function fn4() {
    console.log(1);
    console.log(2);
    console.log(3);
}

fn4();

console log(4);

同理:

function fn5() {
    return new Promise(resolve => {
        console.log(1);
        console.log(2);
        console.log(3);
        resolve()
    })
}

fn(5)
console.log(4);

输出结果:

1

2

3

4


当我们使用await调用函数后,当前函数的后边所有代码会在当前函数执行完毕后,被放入到微任务队列中

fn4( )与fn5( )同理

注:await后边的所有代码,都会放到微任务队列中执行

async function fn4() {
    console.log(1);
    await console.log(2);
    await console.log(3);
    console.log(4);
}

function fn5() {
    return new Promise(resolve => {
        console.log(1);
        // 加了await
        console.log(2);
        // 加了await
        resolve()
    }).then(r => {
        console.log(3);
    }).then(r => {
        console.log(4);
    })
}
fn4() //fn5()

console.log(5)



 输出结果: 

1

2

5

3

4


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值