详解JavaScript中async/await的使用方法


当前第2页 返回上一页

下面是正确的方式:

1

2

3

4

5

6

7

8

9

10

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),

  };

}

更糟糕的是,如果你想要一个接一个地获取项目列表,你必须依赖使用 promises:

1

2

3

4

5

6

7

8

async getAuthors(authorIds) {

  // WRONG, this will cause sequential calls

  // const authors = _.map(

  //   authorIds,

  //   id => await authorModel.fetch(id));// CORRECT

  const promises = _.map(authorIds, id => authorModel.fetch(id));

  const authors = await Promise.all(promises);

}

简而言之,你仍然需要将流程视为异步的,然后使用 await 写出同步的代码。在复杂的流程中,直接使用 promise 可能更方便。

错误处理

promise中,异步函数有两个可能的返回值: resolvedrejected。我们可以用 .then() 处理正常情况,用 .catch() 处理异常情况。然而,使用 async/await方式的,错误处理可能比较棘手。

try…catch

最标准的(也是作者推荐的)方法是使用 try...catch 语法。在 await 调用时,在调用 await 函数时,如果出现非正常状况就会抛出异常,await 命令后面的 promise 对象,运行结果可能是 rejected,所以最好把await 命令放在 try...catch 代码块中。如下例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

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 }

}

在捕捉到异常之后,有几种方法来处理它:

  • 处理异常,并返回一个正常值。(不在 catch 块中使用任何 return 语句相当于使用 return undefined,undefined 也是一个正常值。)
  • 如果你想让调用者处理它,你可以直接抛出普通的错误对象,如 throw errorr,它允许你在 promise 链中使用 async getBooksByAuthorWithAwait() 函数(也就是说,可以像getBooksByAuthorWithAwait().then(...).catch(error => ...) 处理错误); 或者可以用 Error 对象将错误封装起来,如 throw new Error(error),当这个错误在控制台中显示时,它将给出完整的堆栈跟踪信息。
  • 拒绝它,就像 return Promise.reject(error) ,这相当于 throw error,所以不建议这样做。

使用 try...catch 的好处:

  • 简单,传统。只要有Java或c++等其他语言的经验,理解这一点就不会有任何困难。
  • 如果不需要每步执行错误处理,你仍然可以在一个 try ... catch 块中包装多个 await 调用来处理一个地方的错误。

这种方法也有一个缺陷。由于 try...catch 会捕获代码块中的每个异常,所以通常不会被 promise 捕获的异常也会被捕获到。比如:

1

2

3

4

5

6

7

8

9

10

class BookModel {

  fetchAll() {

    cb();    // note `cb` is undefined and will result an exception

    return fetch('/books');

  }

}try {

  bookModel.fetchAll();

} catch(error) {

  console.log(error);  // This will print "cb is not defined"

}

运行此代码,你将得到一个错误 ReferenceError: cb is not defined。这个错误是由console.log()打印出来的的,而不是 JavaScript 本身。有时这可能是致命的:如果 BookModel 被包含在一系列函数调用中,其中一个调用者吞噬了错误,那么就很难找到这样一个未定义的错误。

让函数返回两个值

另一种错误处理方法是受到Go语言的启发。它允许异步函数返回错误和结果。详情请看这篇博客文章:

How to write async await without try-catch blocks in Javascript

简而言之,你可以像这样使用异步函数:

1

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

作者个人不喜欢这种方法,因为它将 Go 语言的风格带入到了 JavaScript 中,感觉不自然。但在某些情况下,这可能相当有用。

使用 .catch

这里介绍的最后一种方法就是继续使用 .catch()

回想一下 await 的功能:它将等待 promise 完成它的工作。值得注意的一点是 promise.catch() 也会返回一个 promise ,所以我们可以这样处理错误:

1

2

3

4

// books === undefined if error happens,

// since nothing returned in the catch statement

let books = await bookModel.fetchAll()

  .catch((error) => { console.log(error); });

这种方法有两个小问题:

  • 它是 promises 和 async 函数的混合体。你仍然需要理解 是promises 如何工作的。
  • 错误处理先于正常路径,这是不直观的。

结论

ES7引入的 async/await 关键字无疑是对J avaScrip t异步编程的改进。它可以使代码更容易阅读和调试。然而,为了正确地使用它们,必须完全理解 promise,因为 async/await 只不过是 promise 的语法糖,本质上仍然是 promise

英文原文地址:https://hackernoon.com/javascript-async-await-the-good-part-pitfalls-and-how-to-use-9b759ca21cda

更多编程相关知识,请访问:编程入门!!

以上就是详解JavaScript中async/await的使用方法的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

javascript事件委托的技术原理

javascript能做哪些特效

小总结 javascript 开发中常见错误解决

es6生成器用法介绍(附示例)

javascript中如何利用filter()对数据进行筛选

10个你可能不知道的很棒的js字符串技巧

js同源策略是什么

javascript与java区别是什么

彻底弄懂javascript执行机制

javascript怎么设置img内容

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...