async 函数

一、什么是async :

        async函数是 使用async 关键字声明的函数。async函数是 AsyncFunction 构造函数的实例, 并且其中允许使用 await 关键字。

二、async的作用;

async 和await 关键字让我们可以用一种更加简洁的方式写出基于Promise 的异步行为,无需刻意地链式调用Promise;

(下面让我们上代码感受一下:)

需求 : 调用 http1 再调用http2 (这里用setTimeOut模拟请求);

依次打印出 :1 ,http1 响应值, http2 响应值,3

        function http1() {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve('请求成功1')
                }, 2000)
            })
        }
        function http2() {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve('请求成功2')
                }, 2000)
            })
        }
        

如果不使用 async await , 只能使用 Promise上的 .then() 方法

      console.log(1)
        http1().then(res1 => {
            console.log('res1', res1)
            return http2()
        }).then(res2 => {
            console.log('res2', res2)
            console.log(3)
        })  

使用async

 async function runAsync() {
            console.log(1)
            let res1 = await http1()
            console.log('res1', res1)
            let res2 = await http2()
            console.log("res2", res2)
            console.log(3)
        }
        runAsync()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值