Reputation: 266
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
Upvotes: 0
Views: 746
Reputation: 1695
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();
};
Since your getValues
function uses an axios function, you should return the promise after axios has completed its operation. Your getValues
should be something like this:
Making getValues
an async
function
const getValues = async() =>{
let res = await axios.get('URL') //Just an instance, change the axios method(GET,POST,PUT) according to your needs.
return res
}
(OR)
Return a promise from getValues
.
const getValues = () =>{
return new Promise((resolve,reject)=>{
axios.get('URL',response=>{
resolve("AXIOS REQUEST COMPLETE")
}
})
}
You can update your getValues
to any of the above-described ways, and call getValues
as shown earlier and it shall work as expected.
Upvotes: 0
Reputation: 4623
submit = async () => {
this.props.toggle();
await this.props.getValue();
this.notify();
this.props.resetValidation();
this.props.disable();
this.props.actionCost();
};
Upvotes: 3
Reputation: 417
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();
};
Upvotes: 0