一点async...await的使用技巧

如何把async用到其他函数上

// async 返回的是一个promise函数
async function getAshColumns(id) {
  const url = `xx/${ id }`
  const res = await fetch(url)
  return await res.json()
}
getAshColumns('test).then(res => {
    console.log('res==>', res)
})
  
async function fun1() {}
const fun2 = async function () {}
const fun3 = async (id) => {}

如何在全局作用域下使用async

// 在全局作用域下使用async是不允许的, 可创建自执行函数
(async() => {
  const data = await fun3()
})()

如何在类的函数上使用async

class Animal{
  async fun5(){
    const res = await fetch('')
    return await res.json()
  }
}
const animal = new Animal()
(async () => {
  const data = await animal.fun5()
})()

如何处理async的错误

async function fun6() {
  const res = fetch('')
  if (res.status != 200) {
    throw new Error(res.info)
  }
}

const fun6Info = async () => {
  try {
    const data = fun6()
  } catch (e) {
    console.log('e==>', e);
  }
}

如何处理代码中的串行并行

const func = async () => {
  // 串行
  const data1 = await getAshColumns(1)
  const data2 = await getAshColumns(2)

  // 并行
  // 两个promise
  const data1Promise = getAshColumns(1)
  const data2Promise = getAshColumns(2)
  const data3 = await data1Promise
  const data4 = await data2Promise
}

如何让多个await执行并行

const func = async () => {
  // promise.all返回的也是Promise 所以可以使用await
  const [ data1, data2 ] = await Promise.all([
    getAshColumns(1),
    getAshColumns(2)
  ])
}

结合await和任意兼容.then()的代码

async function func() {
  // await后如果不跟Promise 会隐示的创建
  const number = await 666
  // 等同于
  // const number = await Promise.resolve(666)
  console.log('number==>', number);
}

循环中使用await

const func = async () => {
  const names = [ 'a', 'b' ]
  for (const name of names) {
    const data = await getAshColumns(name)
  }
}
const func = async () => {
  const names = [ 'a', 'b' ]
  const promises = names.map(x => getAshColumns(x))
  for (const name of promises) {
    const data = await promises
  }
}