异步--await

424 阅读2分钟

1、 await好处

是语法糖,本质上仍然是 promise。
同步编程风格;方便调试;
使用async关键字返回promise对象,可以放心使用.then()或者 await

2、await包装

function awaitWrap(promise){
return promise.then(data => [data, null]).catch(err => [null,err])
}
 //使用 
 const [res,err] =  await awaitWrap(this.$store.dispatch('getSetList',
 {grade: gradeId,type: typeId}))

3、应用注意

避免过于串行化,异步函数之间没依赖可以进行异步,

使用变量存储结果,await结果,或Promise.all()执行并行/循环

//错误方式,这两个获取之间没有依赖
async getBooksAndAuthor(authorId) {
  const books = await bookModel.fetchAll();
  const author = await authorModel.fetch(authorId);
  return {
    author,
    books: books.filter(book => book.authorId === authorId),
  };
}

//正确方式 用变量获取resolve的结果
async getBooksAndAuthor(authorId) {
  const bookPromise = bookModel.fetchAll();
  const authorPromise = authorModel.fetch(authorId);
  const book = await bookPromise;
  const author = await authorPromise;
  return {
    author,
    books: books.filter(book => book.authorId === authorId),
  };
}

Promise.all()使用

// 想要逐个获取物品清单,你必须使用 promise
async getAuthors(authorIds) {
  // 错误方式,导致顺序执行
  // const authors = _.map(
  //   authorIds,
  //   id => await authorModel.fetch(id));
// 正确方式
  const promises = _.map(authorIds, id => authorModel.fetch(id));
  const authors = await Promise.all(promises);
}

4、走出await困境

① 找出那些依赖其它语句执行的语句
② 将相互依赖的语句包在一个 async 函数中
③ 并行执行这些 async 函数

5、 错误处理

  • try…catch 推荐

1)处理异常,并返回一个正常值。(不在 catch 块中使用任何 return 语句相当于使用 return undefined,undefined 也是一个正常值。)
2)如果你想让调用者来处理它,就将它抛出。
     你可以直接抛出错误对象,比如 throw error
     包装成 Error 对象,比如 throw new Error(error)不推荐使用。
调用:await getBooksByAuthorWithAwait()
或者:getBooksByAuthorWithAwait().then(...).catch(error => …)

class BookModel {
  fetchAll() {
    return new Promise((resolve, reject) => {
      window.setTimeout(() => { reject({'error': 400}) }, 1000);
    });
  }
}
// async/await
async getBooksByAuthorWithAwait(authorId) {
try {
  const books = await bookModel.fetchAll();
} catch (error) {
  console.log(error);    // { "error": 400 }
}
  • 数组解构

[err, user] = await to(UserModel.findById(1));

  • .catch

promise.catch() 也会返回一个 promise
错误处理出现在普通代码逻辑之前

let books = await bookModel.fetchAll()
  .catch((error) => { console.log(error); });

6、更清楚的例子,建议看

mp.weixin.qq.com/s/jZa0YEhUo…

本文大多内容来自前端之巅微信公众号,感谢作者的总结。 mp.weixin.qq.com/s/WJUwKgtl0…
hackernoon.com/javascript-…