ES6学习笔记(四)—— async 函数

await 是 async wait 的简写, 是 generator 函数的语法糖。

async 函数的特点:

  • async 声明一个方法是异步的,await 则等待这个异步方法执行的完成
asyncReadFile = async function () {
  var f1 = await readFile('/etc/fstab')
  var f2 = await readFile('/etc/shells')
  console.log(f1.toString())
  console.log(f2.toString())
}
  • await 只能出现在 async 函数中, 用在 async 外或者普通函数内都会报错
function getDay () {
  return new Date().getDay()
}
const today = await getDay ()
// Uncaught SyntaxError: Unexpected identifier
  • async函数返回一个 Promise 对象,如果在函数中 return 一个直接量,async 会把这个直接量通过 Promise.resolve() 封装成 Promise 对象
async function getName () {
  return 'wangxi'
}
getName()
// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "wangxi"}
  • async函数内部return语句返回的值,会成为then方法回调函数的参数
async function getName () {
  return 'wangxi'
}
getName().then(value => console.log(value))
// wangxi
  • 只要一个await语句后面的 Promise 变为reject,那么整个async函数都会中断执行
async function f() {
  await Promise.reject('出错了')
  await Promise.resolve('hello world') // 不会执行
}
f() 
// VM259:4 Uncaught (in promise) 出错了 
  • 如果希望前一个异步操作失败但不会影响后面的异步操作继续进行,可以将前面的 await 放在 try...catch 结构里面(如果有多个 await ,则需要将每一个 await 都放在 try...catch 中)
async function f() {
  try {
    await Promise.reject('出错了')
  } catch(e) {
  }
  return await Promise.resolve('hello world')
}
f().then(v => console.log(v)) 

或者在 await 后面的 Promise 对象加一个 catch 方法来处理错误

async function f() {
  await Promise.reject('出错了').catch(e => console.log(e))
  await Promise.reject('又出错了').catch(e => console.log(e))
  return await Promise.resolve('hello world')
}
f().then(v => console.log(v))
// 出错了
// 又出错了
// hello world
  • 如果多个异步操作不存在继发关系,则可以使用 Promise.all 同时触发异步操作
async function f () {
  // 先后,先执行 getName() 再执行 getAge()
  const name = await getName()
  const age = await getAge()
  console.log(name, wangxi) // wangxi 25
  // 同时触发
  let [name1, age1] = await Promise.all([getName(), getAge()])
  console.log(name1, age1) // wangxi 25
}

参考:http://es6.ruanyifeng.com/#docs/async 

原文地址:https://www.cnblogs.com/wx1993/p/7495180.html