Home > Web Front-end > JS Tutorial > Detailed explanation of how to use async/await in JavaScript

Detailed explanation of how to use async/await in JavaScript

青灯夜游
Release: 2020-11-19 18:04:38
forward
16248 people have browsed it

Detailed explanation of how to use async/await in JavaScript

async/await introduced by ES8 is an excellent improvement in asynchronous programming in JavaScript. It provides a way to access resouces asynchronously using synchronous style code without blocking the main thread. However, they also have some pitfalls and problems. In this article, we will explore async/await from different perspectives and demonstrate how to use these brothers correctly and effectively.

Pre-knowledge

What is the role of async

It can be seen from MDN:

async The function returns a Promise object. async Functions (including function statements, function expressions, Lambda expressions) will return a Promise object. If return is a direct quantity in the function, async will encapsulate this direct value into a Promise object through Promise.resolve().

If the async function does not return a value, it will return Promise.resolve(undefined).

What is the role of await

Learned from MDN:

await What we are waiting for is an expression. This expression The evaluation result is a Promise object or other value (in other words, await can wait for the result of any expression).

If what it waits for is not a Promise object, the result of the await expression is what it waits for.

If it is waiting for a Promise object, await will be busy. It will block the following code, wait for the Promise object to resolve, and then get the resolved value as the result of the await expression.

This is why await must be used in async functions. Async function calls will not cause blocking. All blocking inside them are encapsulated in a Promise object and executed asynchronously.

Advantages of async/await

async/await The most important benefit brought to us is the synchronous programming style. Let's look at an example:

// async/await
async getBooksByAuthorWithAwait(authorId) {
  const books = await bookModel.fetchAll();
  return books.filter(b => b.authorId === authorId);
}// promise
getBooksByAuthorWithPromise(authorId) {
  return bookModel.fetchAll()
    .then(books => books.filter(b => b.authorId === authorId));
}
Copy after login

Obviously, the async/await version is easier to understand than the promise version. If you omit the await keyword, the code will look like any other synchronous language, such as Python.

The best part is not only readability. async/await As of today, all major browsers fully support async functionality.

Detailed explanation of how to use async/await in JavaScript

Native browser support means you don’t have to switch codes. More importantly, it facilitates debugging. When you set a breakpoint at the function entry point and step over the await line, you will see the debugger pause for a moment while bookModel.fetchAll() performs its task, and then it will move to Next .filter line, this is much simpler than promise code, in promise it must be in .filter Set another breakpoint on line .

Detailed explanation of how to use async/await in JavaScript

Another less obvious advantage is the async keyword. asyncStatementgetBooksByAuthorWithAwait()The function return value is guaranteed to be a promise, so the caller can safely use getBooksByAuthorWithAwait() .then(...) or await getBooksByAuthorWithAwait(). Consider the following example (bad practice!):

getBooksByAuthorWithPromise(authorId) {
  if (!authorId) {
    return null;
  }
  return bookModel.fetchAll()
    .then(books => books.filter(b => b.authorId === authorId));
}
Copy after login

In the above code, getBooksByAuthorWithPromise may return promise (normally) or null value (in exceptional circumstances), in exceptional circumstances, the caller cannot call .then(). With the async statement, this situation will not occur.

async/await can be misleading

Some articles compare async/wait to Promise and claim it is the next generation of JavaScript Asynchronous programming style, which the author deeply disagrees with. async/await is an improvement, but it is just syntactic sugar and will not completely change our programming style.

Essentially, the async function is still a promise. You have to understand promise before you can use async functions correctly, and even worse, most of the time you need to use along with promises async functions.

Consider the getBooksByAuthorWithAwait() and getbooksbyauthorwithpromise() functions in the example above. Note that not only are they functionally identical, they have the exact same interface!

This means that getbooksbyauthorwithwait() will return a promise, so ## can be used as well #.then(...) way to call it.

嗯,这未必是件坏事。只有 await 的名字给人一种感觉,“哦,太好了,可以把异步函数转换成同步函数了”,这实际上是错误的。

async/await

那么在使用 async/await 时可能会犯什么错误呢?下面是一些常见的例子。

太过串行化

尽管 await 可以使代码看起来像是同步的,但实际它们仍然是异步的,必须小心避免太过串行化。

async getBooksAndAuthor(authorId) {
  const books = await bookModel.fetchAll();
  const author = await authorModel.fetch(authorId);
  return {
    author,
    books: books.filter(book => book.authorId === authorId),
  };
}
Copy after login

上述代码在逻辑上看似正确的,然而,这是错误的。

  1. await bookModel.fetchAll() 会等待 fetchAll() 直到 fetchAll() 返回结果。
  2. 然后 await authorModel.fetch(authorId) 被调用。

注意,authorModel.fetch(authorId) 并不依赖于 bookModel.fetchAll() 的结果,实际上它们可以并行调用!然而,用了 await,两个调用变成串行的,总的执行时间将比并行版本要长得多得多。

下面是正确的方式:

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),
  };
}
Copy after login

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

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);
}
Copy after login

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

错误处理

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

try…catch

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

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 }
}
Copy after login

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

  • 处理异常,并返回一个正常值。(不在 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 捕获的异常也会被捕获到。比如:

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"
}
Copy after login

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

让函数返回两个值

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

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

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

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

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

使用 .catch

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

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

// books === undefined if error happens,
// since nothing returned in the catch statement
let books = await bookModel.fetchAll()
  .catch((error) => { console.log(error); });
Copy after login

这种方法有两个小问题:

  • 它是 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

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

The above is the detailed content of Detailed explanation of how to use async/await in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template