Home > Web Front-end > Vue.js > body text

How to use async/await to handle asynchronous operations in Vue

WBOY
Release: 2023-06-11 09:18:11
Original
5098 people have browsed it

How to use async/await to handle asynchronous operations in Vue

With the continuous development of front-end development, we need to handle more complex asynchronous operations in Vue. Although Vue already provides many convenient ways to handle asynchronous operations, in some cases, we may need to use a simpler and more intuitive way to handle these asynchronous operations. At this time, async/await becomes a very good choice.

What is async/await?

In ES2017, async and await become two new keywords. async is used to modify a function to indicate that the function is an asynchronous function. In an asynchronous function, we can use await to wait for a Promise object and then obtain the value of the object.

In Vue, we usually use some Promise-based asynchronous operations, such as calling interfaces to obtain data, or asynchronously loading images, etc. Using async/await allows us to handle these asynchronous operations more clearly.

How to use async/await?

The basic syntax for using async/await is very simple. We only need to declare a function as an async function, and then use await to wait for the return value of the Promise object where we need to wait for asynchronous operations.

Taking data acquisition as an example, we can define an asynchronous function getArticleById, and then wait for the return value of the http request in the function body:

async function getArticleById(id) {
    const response = await fetch(`/api/articles/${id}`);
    return response.json();
}
Copy after login

In Vue, we usually use axios to call the interface retrieve data. We can encapsulate axios into an asynchronous function, and then use async/await in the Vue component to obtain data.

Taking getting the blog list as an example, we can define an asynchronous function getBlogList:

async function getBlogList() {
    const response = await axios.get('/api/blogs');
    return response.data;
}
Copy after login

Then, in the Vue component, we can use async/await to get the data and bind the data Into the template:

<template>
    <div>
        <div v-for="blog in blogs" :key="blog.id">{{blog.title}}</div>
    </div>
</template>

<script>
    async function getBlogList() {
        const response = await axios.get('/api/blogs');
        return response.data;
    }

    export default {
        data() {
            return {
                blogs: []
            }
        },
        async mounted() {
            this.blogs = await getBlogList();
        }
    }
</script>
Copy after login

Use async/await to handle multiple asynchronous operations

In actual development, we usually encounter situations where multiple asynchronous operations need to be processed at the same time. For example, in Vue components, we need to get data from different interfaces and then process or render it. At this time, we can use the Promise.all() method to wait for all asynchronous operations to be completed at once.

Taking getting articles and comments as an example, we can define two asynchronous functions getArticle and getComments:

async function getArticle(id) {
    const response = await axios.get(`/api/articles/${id}`);
    return response.data;
}

async function getComments(articleId) {
    const response = await axios.get(`/api/articles/${articleId}/comments`);
    return response.data;
}
Copy after login

Then, we can encapsulate these two asynchronous operations into an async function, using Promise.all() waits for both operations to complete at the same time:

async function getArticleWithComments(articleId) {
    const [ article, comments ] = await Promise.all([
        getArticle(articleId),
        getComments(articleId)
    ]);
    return {
        article,
        comments
    };
}
Copy after login

In the Vue component, we can use async/await to get all the data and bind the data to the template:

<template>
    <div>
        <h1>{{article.title}}</h1>
        <p>{{article.content}}</p>
        <ul>
            <li v-for="comment in comments" :key="comment.id">{{comment.content}}</li>
        </ul>
    </div>
</template>

<script>
    async function getArticle(id) {
        const response = await axios.get(`/api/articles/${id}`);
        return response.data;
    }

    async function getComments(articleId) {
        const response = await axios.get(`/api/articles/${articleId}/comments`);
        return response.data;
    }

    async function getArticleWithComments(articleId) {
        const [ article, comments ] = await Promise.all([
            getArticle(articleId),
            getComments(articleId)
        ]);
        return {
            article,
            comments
        };
    }

    export default {
        data() {
            return {
                article: {},
                comments: []
            }
        },
        async mounted() {
            const data = await getArticleWithComments(this.$route.params.articleId);
            this.article = data.article;
            this.comments = data.comments;
        }
    }
</script>
Copy after login

Use try/catch to handle exceptions

When using async functions, we also need to pay attention to exception handling. When an error occurs in an asynchronous function, we can use the try/catch statement to catch the exception and handle it accordingly.

Taking obtaining user information as an example, we can define an asynchronous function getUserInfo. If the user is not logged in, an unauthorized error will be returned when obtaining user information from the server. We can use the try/catch statement to capture the error and handle it accordingly:

async function getUserInfo() {
    try {
        const response = await axios.get('/api/user');
        return response.data;
    } catch (error) {
        if (error.response && error.response.status === 401) {
            // 用户未登录
            return null;
        } else {
            // 其它异常
            throw error;
        }
    }
}
Copy after login

In the Vue component, we can use async/await to obtain user information and handle it accordingly based on the return value:

<template>
    <div>
        <div v-if="user">{{user.name}},欢迎回来!</div>
        <div v-else>请先登录</div>
    </div>
</template>

<script>
    async function getUserInfo() {
        try {
            const response = await axios.get('/api/user');
            return response.data;
        } catch (error) {
            if (error.response && error.response.status === 401) {
                // 用户未登录
                return null;
            } else {
                // 其它异常
                throw error;
            }
        }
    }

    export default {
        data() {
            return {
                user: null
            }
        },
        async mounted() {
            this.user = await getUserInfo();
        }
    }
</script>
Copy after login

Summary

Using async/await allows us to handle asynchronous operations in Vue more clearly. We can use async/await to wait for the return value of the Promise object, and use Promise.all() to wait for multiple asynchronous operations to complete at once. At the same time, when using asynchronous functions, you also need to pay attention to exception handling. You can use try/catch statements to catch exceptions in asynchronous operations.

The above is the detailed content of How to use async/await to handle asynchronous operations in Vue. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!