在开发中,可能会遇到两个或多个函数异步执行的情况,对于Vue中函数的异步函数执行做了一个

小总结,如下:

​异步执行使用async和await完成。

created() {
    this.init()
},
methods: {
    async init(){
       await this.getList1();
       this.getList();
    },
     // 函数1
     getList(){
        return 'hello world';
     }
     // 函数2
     async getList1(){
        return '虽然在后面,但是我先执行';
    }
}

1、async基础用法

1. async函数,会返回一个promise对象,可以用.then调用async函数中return的结果

  async function helloAsync() {
        return "返回结果";
    }
    console.log(helloAsync()) // 输出Promise对象: Promise {<fulfilled>: '返回结果'}
    helloAsync().then(v => {
        console.log(v); // 输出:返回结果
    })

2. async函数中,可以使用await表达式,async函数执行,遇到await,会先暂停,等到await后的异步执行完毕,再继续往后执行

    // 1.使用await
    function testAwait() {
        return new Promise((resolve) => {
            setTimeout(function () {
                console.log("异步中的输出");
                resolve();
            }, 1000);
        });
    }
    async function helloAsync() {
        await testAwait();  // 等待异步
        console.log("async中的输出");
    }
    helloAsync(); // 输出:先输出"异步中的输出",再输出"async中的输出"
    
    // 2.不使用await
    function testAwait() {
        return new Promise((resolve) => {
            setTimeout(function () {
                console.log("异步中的输出");
                resolve();
            }, 1000);
        });
    }
    async function helloAsync() {
        testAwait();
        console.log("async中的输出");
    }
    helloAsync(); // 输出:先输出"async中的输出",再输出"异步中的输出"

2、解析

async:表示函数是异步执行

await:表示当前函数先执行,执行完之后,再执行其他函数

await用于等待一个promise对象,它只能在async函数中使用

本文来自博客园,作者:喆星高照,转载请注明原文链接:

https://www.cnblogs.com/houxianzhou/p/16397095.html

GitHub 加速计划 / vu / vue
207.53 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 4 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐