美文网首页
async/await

async/await

作者: VickyFan | 来源:发表于2018-11-25 11:13 被阅读0次

上周我们写到用回调或者then处理异步操作,这周我们体验一下使用async/await来处理异步

1.什么是async/await?

async是“异步”的意思,async function 声明用于定义一个返回promise对象的异步函数
。而await从字面意思上是“等待”的意思,就是用于等待异步完成。并且await与async是配套使用,即只能在async函数中使用。await得到Promise对象之后就等待Promise接下来的resolve或者reject。

// 
async function asyncFun() {
  return 'hello async'
}
console.log(asyncFun ())
image.png

从上面的返回结果我们可以看到,如果async直接返回的是一个return值,那么他会封装成peomise中的resolved。
若我们就是想要这个返回值怎么办呢?就像上周peomise提到的then用法

async function asyncFun() {
  return 'hello async'
}
asyncFun().then((value) => {
  console.log(value) // hello async
})
image.png

2.实际应用中return返回了一个undefined怎么办?

在一些实际应用中,我们想要把接口请求回来的数据,渲染到页面,并且要执行下一步操作时,我们肯定会想到用异步处理,但是我们不知道请求接口会花费多少时间,万一还没有返回数据,渲染上去的就是undefined,页面肯定会报错。
例子:

async getGroupConfig (val) {
      this.modifyGroup.loading = true
      const url = '/Document/getGroupDetail'
      const finUrl = '/Document/getStaffInfoByCenter'
      try {
        let modifyGroup = this.modifyGroup
        let req = {
          params: {
            id: val
          }
        }
        let {error, msg} = await this.$axios.get(url, req)
        if (error) {
          this.$message.warning(msg)
          return
        }
        modifyGroup.id = msg.id
        modifyGroup.name = msg.name
        modifyGroup.department = msg.centerTree.split(',').map(ele => ele.split('#'))
        modifyGroup.centerId = msg.centerId.split(',')
        modifyGroup.extraStaff = msg.extraStaff.map(ele => ele.staffId)
        modifyGroup.extraStaffOption = msg.extraStaff
        modifyGroup.removeStaff = msg.removeStaff.map(ele => ele.staffId)
        let reqParams = {
          params: {
            centerId: msg.centerId
          }
        }
        let res = await this.$axios.get(finUrl, reqParams)
        if (res.error) {
          this.$message.warning(res.msg)
          return
        }
        modifyGroup.removeStaffOption = res.msg
        this.modifyGroup.loading = false
      } catch (err) {
        this.modifyGroup.loading = false
        console.log(err)
      }
    },

在上面例子我们可以看到,首先是请求‘/Document/getGroupDetail'这个接口,返回的结果作为第二个接口/Document/getStaffInfoByCenter的参数。若返回的是ubdefined,那么在请求第二个接口时必将报错,这是我们就用到await

3.await帮我们做了什么?

首先,await 操作符用于等待一个Promise 对象。它只能在异步函数 async function 中使用。
其次,await是在等待acync函数的完成,其获取到的是一个promise的计算结果,即一个真正的实际返回值。
例如:还是看上面的例子

let {error, msg} = await this.$axios.get(url, req)

4.通过async方法重写 promise 链

上周的promise中,在多个业务中,我们使用多个then进行多次的处理,这样使用起来特别麻烦。

newPromise1().then((data) => {
    console.log(data)
    return newPromise2()
  }).then((data) => {
    throw new Error('Something failed')
    console.log('Do this')
    return newPromise3()
  }).catch(() => {
    console.log('Do what')
  }).then((data) => {
    console.log(data)
  })

但是我们可以通过上面第一个例子中的await写法:

async getGroupConfig (val) {
    let {error, msg} = await this.$axios.get(url, req)
    let res = await this.$axios.get(finUrl, reqParams)
}

5.错误处理

正常:promise正常resolve,那么await返回这个结果
异常:但是在reject的情况下会抛出一个错误

async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url); 
  } catch (e) {
    v = await downloadFallbackData(url);
  }
  return processDataInWorker(v);
}

相关文章

  • async和await

    浅谈Async/Await用 async/await 来处理异步 async和await async:声明一个异步...

  • ES8(一) —— async&await

    目录 async和普通函数的区别 await async/await处理多回调异步 async和await必须配合...

  • async

    async/await特点 async/await更加语义化,async是“异步”的简写,async functi...

  • ES6中的好东西

    1 Await/Async 前端的回调时代我没有赶上,我赶上的是await/async时代。await和async...

  • Vue接口调用方式(三)async/await用法

    async/await用法 1. async/await的基本用法 async/await是ES7引入的新语法,可...

  • nodejs async 使用简介

    async await node async 使用

  • JS 中的 async/await

    async/await 是什么? async/await 是 ES2017 中新增的异步解决方案; await 只...

  • ES2017 async 函数

    async 和 await 在干什么 每个名称都有意义async : 异步await: async wait简...

  • async/await

    async/await async/await 是Generator的语法糖。 Generator 通过将Gene...

  • 小程序-云开发

    async和await async:异步(无等待)await:等待(是为了同步) 一、await 关键字只在 as...

网友评论

      本文标题:async/await

      本文链接:https://www.haomeiwen.com/subject/iniuqqtx.html