在开发中,可能会遇到两个或多个函数异步执行的情况,对于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

Logo

一站式 AI 云服务平台

更多推荐