Home > front end >  How to run functions one after the other after one function has fully executed when functions are bo
How to run functions one after the other after one function has fully executed when functions are bo

Time:10-25

I am new to react and am trying to run functions one after the other.

This is my code:

submit = () => {
    this.props.toggle();
    this.props.getValue(); 
    this.notify();
    this.props.resetValidation();
    this.props.disable();
    this.props.actionCost();
};

Here getValue is an asynchronous function and notify is a react toastify function, rest are synchronous function. I want to run getValue first and then run all the other functions after it has been executed. How do I do that. Presently all functions are running simultaneously

Please help

CodePudding user response:

 submit = async () => {
    this.props.toggle();
    await this.props.getValue(); 
    this.notify();
    this.props.resetValidation();
    this.props.disable();
    this.props.actionCost();
};

CodePudding user response:

Since getValue is an async function, it returns a Promise object, and you want other functions to be executed after getValue has completed it's execution, you can either use .then() or await on getValue.
Using .then().

 submit = () => {
    
    this.props.getValue().then(res=>{
      this.props.toggle();  //All these functions execute only after getValue has completed it's execution.
      this.notify();
      this.props.resetValidation();
      this.props.disable();
      this.props.actionCost();
    })
};

Using await

submit = async() => {
    await this.props.getValue();  //Note that this should be placed on top as this is the function you want to run first, and other functions to execute only after this has completed.
    this.props.toggle();
    this.notify();
    this.props.resetValidation();
    this.props.disable();
    this.props.actionCost();
};

CodePudding user response:

You should define the submit method as an async method and it will be like this:

submit = async () => {
    this.props.toggle();
    await this.props.getValue(); 
    this.notify();
    this.props.resetValidation();
    this.props.disable();
    this.props.actionCost();
};
  • Related