async & await &promise

async

  • async 的本质就是会隐式的返回一个 Promise 对象
const getInfo = async () => {
  return 'hello world'
}
getInfo() // Promise {<fulfilled>: "hello world"}
  • 声明为 async 的函数,默认的返回值就是一个 Promise 对象,等同于
const getInfo = async () => {
  return Promise.resolve('hello world')
}
getInfo()  // Promise {<fulfilled>: "hello world"}
  • async声明function是一个异步函数,返回一个promise对象,可以使用 then 方法添加回调函数
  • async函数内部return语句返回的值,会成为then方法回调函数的参数
const getInfo = async () => {
  return Promise.resolve('hello world')
}
getInfo().then(res => {
  console.log(res) // hello world
})
  • async函数返回的 Promise 对象被reject,可以在catch中捕获
const getInfo = async () => {
  return Promise.reject('出错了')
}
getInfo().then(res => {
  console.log(res)
}).catch(err => {
  console.log(err) // 出错了
})

await

  • await 操作符只能在异步函数 async function 内部使用
  • 如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果,也就是说它会阻塞后面的代码,等待 Promise 对象结果
  • 如果等待的不是 Promise 对象,则返回该值本身
const getMsg1 = () => {
  return Promise.resolve('test1')
}

const getMsg2 = () => {
  return Promise.resolve('test2')
}
const resultMsg = async () => {
  const [p1, p2] = await Promise.all([getMsg1(), getMsg2()])
  console.log(p1, p2)
}
resultMsg()
console.log('我先执行')
执行结果:'我先执行' -> 'test1 test2'

错误处理

  • 如果await后面的异步操作出错,那么等同于async函数返回的 Promise 对象被reject
  • 防止出错的方法,也是将其放在try...catch代码块之中
const getMsg1 = () => {
  return Promise.resolve('test1')
}

const getMsg2 = () => {
  return Promise.reject('出错了')
}
const resultMsg = async () => {
  try {
    const [p1, p2] = await Promise.all([getMsg1(), getMsg2()])
    if (p1 && p2) {
       console.log(p1, p2)
    }
  } catch (e) {
    console.log(e)
  }
}
resultMsg()

模拟接口

  // 模拟接口
  function request() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {

        const res = {
          code: 200,
          data: [{
            name: 'zhang',
            age: 10
          }]
        }

        if (res && res.code === 200) {
          resolve(res)
        } else {
          reject('请求失败')
        }
      }, 3000)
    })
  }

  // 请求接口
  const getInfo = async () => {
    try {
      let res = await request()
      if (res && res.code === 200) {
          console.log(res.data)
      }
    } catch (err) {
      console.log(err)
    }
  }

  getInfo()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • async作用 async声明function是一个异步函数,返回一个promise对象,可以使用 then 方法...
    关航_强化班阅读 3,446评论 0 0
  • [注:以下代码都在支持 Promise 的 Node 环境中实现] 1 promise 释义 promise 是抽...
    夏暮阅读 3,899评论 0 0
  • async/await 是一种特殊的语法,能够更好的处理promise,可以让你编写基于Promise的代码像同步...
    一蓑烟雨任平生_cui阅读 3,848评论 0 2
  • 一、什么是promise,及其作用 Promise是ES6中的一个内置对象,实际是一个构造函数,是JS中进行异步编...
    涅槃快乐是金阅读 13,721评论 0 8
  • 一、概念 async定义异步函数 自动把函数转为promise 当调用异步函数的时候,函数返回值会被resolve...
    Joy_c914阅读 9,087评论 0 0