ES6 async 与 await

一、 async

async 和 await 两种语法结合可以让异步代码像同步代码一样

async 函数:

1. async 函数的返回值为 promise 对象

2. promise 对象的结果由 async 函数执行的结果决定

        // async 函数
        async function fn(){
            // return 一个字符串
            // return '凹凸曼'
            // return 的不是一个 Promise 类型的对象 返回的结果就是成功的 Promise 对象
            // return
            // 抛出错误 返回的结果是一个失败的 Promise
            // throw new Error('错误啦')
            // 返回的结果如果是一个 Promise 对象
            return new Promise((resolve, reject) => {
                resolve('成功的数据')
                // reject('失败的错误')
            })
        }

        const result = fn()

        // 调用 then 方法
        result.then(value => {
            console.log(value)
        }, reason => {
            console.warn(reason)
        })

二、 await

await 表达式

1. await 必须写在 async 函数中

2. await 右侧的表达式一般为 promise 对象

3. await 返回的是 primise 对象

4. await 的 promise 失败了,就会抛出异常,需要通过 try...catch 捕获处理

        // 创建 promise 对象
        const p = new Promise((resolve, reject) => {
            // resolve('成功的值!')
            reject('失败啦!')
        })

        // await 要放在 async 函数中
        async function main(){
            try {
                let result = await p
                console.log(result)
            } catch (error) {
                console.log(error)
            }
        }
        // 调用函数
        main()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值