Home >Web Front-end >JS Tutorial >A brief analysis of JS's asynchronous function async/await

A brief analysis of JS's asynchronous function async/await

青灯夜游
青灯夜游forward
2023-01-28 19:17:192486browse

This article will introduce you to JavaScript’s asynchronous function async/await. I hope it will be helpful to you!

A brief analysis of JS's asynchronous function async/await

async/await introduced in ES7 is an improvement to JavaScript asynchronous programming. It provides the option to access resources asynchronously using synchronous style code. without blocking the main thread. However, it's a little tricky to use it well. In this article, we will explore async/await from different perspectives and show how to use them correctly and efficiently.

async/await benefits

async/await The most important benefit is the synchronous programming style. Let’s look at an example first.

// async/await
const getArticlesByAuthorWithAwait = async (authorId) => {
    const articles = await articleModel.fetchAll();
    return articles.filter((b) => b.authorId === authorId);
};

// promise
const getArticlesByAuthorWithPromise = (authorId) => {
    return articleModel
        .fetchAll()
        .then((articles) => articles.filter((b) => b.authorId === authorId));
};

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.

At the same time async/await is supported by native browsers. As of now, all major browsers have fully supported asynchronous functions.

It should be noted that async/await needs to appear in pairs during use. If await is used in a function, the function must be Defined as async.

async/await can be misleading

Some articles compare async/await to Promise , and claims that it is the next generation of JavaScript asynchronous programming, which I personally think is a bit misleading. I personally think async/await is an improvement, a syntactic sugar, and will not completely change the programming style.

Essentially, asynchronous functions are still promises. Before using asynchronous functions correctly, you must understand promises.

async/await pitfalls

Although await can make code look synchronous, remember that they are still asynchronous and care must be taken to avoid being too sequential.

const getArticlesAndAuthor = async (authorId) => {
    const articles = await articleModel.fetchAll();
    const author = await authorModel.fetch(authorId);
    return {
        author,
        articles: articles.filter((article) => article.authorId === authorId),
    };
};

This code seems to be logically correct, but it is misleading.

  • await articleModel.fetchAll() will wait until fetchAll() returns.

  • Then await authorModel.fetch(authorId) will be called immediately.

Error handling

Using promise, the asynchronous function has two possible return values: resolve and reject, for normal cases use .then() and for exception cases use .catch(). However, async/await error handling is not very good, you need to use try...catch to catch exceptions.

const getArticlesByAuthorWithAwait = async (authorId) => {
    try {
        const articles = await articleModel.fetchAll();
        return articles.filter((b) => b.authorId === authorId);
    } catch (error) {
        // 错误处理
    }
};

Summary

async/await is very powerful, but there are some caveats. But if used correctly, they can still help make the code efficient and highly readable.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of A brief analysis of JS's asynchronous function async/await. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete