首页 > 解决方案 > 在javascript中的异步函数之后运行函数

问题描述

我试图编写一个运行异步函数的代码,完成后,它运行另一段代码。

我尝试将 async 函数放入一个 Promise 中(如下面的代码所示)并使用该then方法但没有成功。

函数内部发生的事情并不重要,但无论如何我都已经包含了它,以防我弄错了,它确实..

getData = async(file) =>{
        let data = await fetch(file);
        data = await data.text();
        return(data);
    }

    getDataAndUsername = async() => {
        this.setState({data: JSON.parse(await this.getData("/getData"))});
        this.setState({username: await this.getData("/user")});
        console.log('done');
    }

getDataAndUsername 是我试图在其他函数之前运行的异步函数。

CheckInDataBase = (username) => {
        console.log('checking In DataBase');
        this.state.data.forEach((element)=>{
            if(element.username === username){
                    this.setState({exist: true});
                }
            });
            if (!(this.state.exist)){
            axios.post('/createUser', {"username": username, "status": "Working"});
            this.setState({exist: true});
        }
        }

这是我试图在异步之后运行的常规功能

这是代码:

new Promise((res) => {
            this.getDataAndUsername();
            res();
        }).then(
            this.CheckInDataBase(this.state.username)
        )

现在发生的事情是 this.CheckInDatabase 在 getDataAndUsername 完成之前运行。

标签: javascriptreactjsasynchronous

解决方案


被定义为async,你getDataAndUsername的已经是一个 Promise,没有必要把它包装在new Promise(). 你可以这样做:

this.getDataAndUsername().then( _ => {
  this.CheckInDataBase(this.state.username);
})

它应该工作。

为什么你的代码一开始就不起作用

你正在用这个创建一个新的承诺:

new Promise((res) => {
            this.getDataAndUsername();
            res();
        }) ...

在那里,你打电话this.getDataAndUsername(),但忽略它是否解决。该代码将 res立即调用,因此在解决checkInDatabase之前被调用。getDataAndUsername

你冷,相反,等待getDataAndUsername解决:

new Promise((res) => {
            return this.getDataAndUsername().then(_ => {res()})
        }) ...

关键是等待承诺解决使用then,并添加return.

但是,如上所述,没有必要这样做,因为getDataAndUsername它已经是一个 Promise。


推荐阅读