ES6新特性-用 async/await 来处理异步

ES6新特性-用 async/await 来处理异步

  • 用async/ await来发送异步请求,从服务端获取数据
  • async的用法:作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行
写法:
async function timeout() {
  return 'hello world';
}
  • 证明没有阻塞它后面代码的执行:
async function timeout() {
    return 'hello world'
}
timeout();
console.log('虽然在后面,但是我先执行');

打开浏览器看打印:
在这里插入图片描述
看timeout打印出什么

async function timeout() {
    return 'hello world'
}
console.log(timeout());
console.log('虽然在后面,但是我先执行');

在这里插入图片描述
原来async 函数返回的是一个promise 对象,如果要获取到promise 返回值,我们应该用then方法, 继续修改代码

async function timeout() {
    return 'hello world'
}
timeout().then(result => {
    console.log(result);
})
console.log('虽然在后面,但是我先执行');

在这里插入图片描述
可能注意到控制台中的Promise 有一个resolved,这是async 函数内部的实现原理。
如果async 函数中有返回一个值 ,当调用该函数时,内部会调用Promise.solve() 方法把它转化成一个promise 对象作为返回,但如果timeout 函数内部抛出错误呢? 那么就会调用Promise.reject() 返回一个promise 对象。

async function timeout(flag) {
    if (flag) {
        return 'hello world'
    } else {
        throw 'my god, failure'
    }
}
console.log(timeout(true))  // 调用Promise.resolve() 返回promise 对象。
console.log(timeout(false)); // 调用Promise.reject() 返回promise 对象。

在这里插入图片描述
如果函数内部抛出错误, promise 对象有一个catch 方法进行捕获。

timeout(false).catch(err => {
    console.log(err)
})
  • await 用法:
    await 关键字只能放到async 函数里面
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2 * num)
        }, 2000);
    } )
}

现在再写一个async 函数,从而可以使用await 关键字, await 后面放置的就是返回promise对象的一个表达式,所以它后面可以写上 doubleAfter2seconds 函数的调用

async function testResult() {
    let result = await doubleAfter2seconds(30);
    console.log(result);
}

现在我们看看代码的执行过程,调用testResult 函数,它里面遇到了await, await 表示等一下,代码就暂停到这里,不再向下执行了,它等什么呢?等后面的promise对象执行完毕,然后拿到promise resolve 的值并进行返回,返回值拿到之后,它继续向下执行。具体到 我们的代码, 遇到await 之后,代码就暂停执行了, 等待doubleAfter2seconds(30) 执行完毕,doubleAfter2seconds(30) 返回的promise 开始执行,2秒 之后,promise resolve 了, 并返回了值为60, 这时await 才拿到返回值60, 然后赋值给result, 暂停结束,代码才开始继续执行,执行 console.log语句。

async function testResult() {
    let first = await doubleAfter2seconds(30);
    let second = await doubleAfter2seconds(50);
    let third = await doubleAfter2seconds(30);
    console.log(first + second + third);  //220
}
  • 它用的是try/catch 来捕获异常,把await 放到 try 中进行执行,如有异常,就使用catch 进行处理。
   async getFaceResult () {
         try {
             let location = await this.getLocation(this.phoneNum);
             if (location.data.success) {
                 let province = location.data.obj.province;
                 let city = location.data.obj.city;
                 let result = await this.getFaceList(province, city);
                 if (result.data.success) {
                     this.faceList = result.data.obj;
                 }
             }
         } catch(err) {
             console.log(err);
         }
     }
  • 项目中遇到
   //提交
    async completeAndSubmit() {
      console.log('completeAndSubmit')
      try {
        //如果用户直接选择"到访不遇",则不进入后续流程
        if (this.startForm.householdSituation === 0) {
          let result1 = await this.addTask()
          this.$vux.toast.show({
            type: 'text',
            text: '提交成功!'
          })
          this.can_exit = true
          this.goBack()
        } else {
          //如果用户选择"成功入户"
          let result1 = await this.addTask()
          let result2 = await this.upLoadCheckItemsResult()
          let result3 = await this.upLoad_customerSignature()
          let result4 = await this.addTaskChecks()
          this.$vux.toast.show({
            type: 'text',
            text: '提交成功!'
          })
          this.can_exit = true
          this.goBack()
        }
      } catch (error) {
        console.log('怎么回事', error)
        this.$vux.toast.show({
          type: 'text',
          text: `${error},请重试!`
        })
      }
    },

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值