Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中异步函数之后运行函数_Javascript_Reactjs_Asynchronous - Fatal编程技术网

javascript中异步函数之后运行函数

javascript中异步函数之后运行函数,javascript,reactjs,asynchronous,Javascript,Reactjs,Asynchronous,我正在尝试编写一个运行异步函数的代码,完成后,它将运行另一段代码 我尝试过将异步函数放在一个承诺中(如下面的代码所示),并使用then方法,但没有成功 函数内部发生的事情其实并不重要,但我已经将其包括在内,以防我弄错,它确实如此。 getDataAndUsername是我尝试在其他函数之前运行的异步函数 CheckInDataBase = (username) => { console.log('checking In DataBase'); this.st

我正在尝试编写一个运行异步函数的代码,完成后,它将运行另一段代码

我尝试过将异步函数放在一个承诺中(如下面的代码所示),并使用
then
方法,但没有成功

函数内部发生的事情其实并不重要,但我已经将其包括在内,以防我弄错,它确实如此。

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完成之前运行。

尝试:

this.getDataAndUsername().then((response) => {
  /**
   * Your code that you want to run after getDataAndUsername
   */
}, (error) => {
  /**
   * Handle error here
   */
});
或使用
异步/等待

(async function() {
  try {
    const dataAndUsername = await this.getDataAndUsername();
    /**
     * Your code that you want to run after getDataAndUsername
     */

  } catch(e) {
    /**
   * Handle error here
   */
  }
})();

由于定义为
async
,您的
getDataAndUsername
已经是一个承诺,因此无需将其包装为
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()})
        }) ...
关键是要等待承诺使用
然后
解析,并添加
返回


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

正如我在评论中所写,您太频繁地更新状态。这是一个异步进程,因此您可能会通过检查或循环旧状态来结束

我建议您尽可能少地使用
this.setState
,并以尽可能多的函数返回值。这样,您将拆分功能,而不依赖react的状态

以下是我对你的问题的建议:

class App extends React.PureComponent {
  getData = async (file) =>{
    let data = await fetch(file);
    return await data.text();
  };

  getDataAndUsername = async () => ({
    data: JSON.parse(await this.getData("/getData")),
    username: JSON.parse(await this.getData("/user"))
  });

  checkInDataBase = ({ username, data }) => {
    console.log('checking In DataBase');
    return !!data.find(element => element.username === username);
  };

  addUser = async username => await axios.post('/createUser', {"username": username, "status": "Working"});

  myCheckFunction = async () => {
    const dataAndUsername = await this.getDataAndUsername();
    if (dataAndUsername) {
      if (!this.checkInDataBase(dataAndUsername)) {
        const newUser = await this.addUser(dataAndUsername.username);
        dataAndUsername.data.push(newUser);
      }
      // A single place where you update the state
      this.setState({
        ...dataAndUsername,
        exists: true
      })
    }
  }
}

为什么不等待这个?@sjahan因为它们不在异步函数中,我不能确定您在函数中太频繁地使用此.setState。它是异步工作的。尝试返回值,而不是更新状态
CheckInDataBase
可能有问题:this.setState({exist:true})的
executes@eitanr如果您的函数正在等待某些内容,那么它是
async
,那么为什么不给它
async
关键字呢?这是有线的。。我记得我试过这个,但它不起作用,但无论如何它现在起作用了,非常感谢!非常感谢您的深入回答!你真的帮了大忙!仍然存在问题:
this.getDataAndUsername()
异步更新状态,并且存在
this.CheckInDataBase(this.state.username)
的风险。
this.state.username
this.state.data
在循环使用
data
时可能会过时,在这种情况下功能将崩溃非常感谢您花时间帮助我重新调整并解决我的错误!你真的帮了大忙!
class App extends React.PureComponent {
  getData = async (file) =>{
    let data = await fetch(file);
    return await data.text();
  };

  getDataAndUsername = async () => ({
    data: JSON.parse(await this.getData("/getData")),
    username: JSON.parse(await this.getData("/user"))
  });

  checkInDataBase = ({ username, data }) => {
    console.log('checking In DataBase');
    return !!data.find(element => element.username === username);
  };

  addUser = async username => await axios.post('/createUser', {"username": username, "status": "Working"});

  myCheckFunction = async () => {
    const dataAndUsername = await this.getDataAndUsername();
    if (dataAndUsername) {
      if (!this.checkInDataBase(dataAndUsername)) {
        const newUser = await this.addUser(dataAndUsername.username);
        dataAndUsername.data.push(newUser);
      }
      // A single place where you update the state
      this.setState({
        ...dataAndUsername,
        exists: true
      })
    }
  }
}