Reputation: 266
I am new to react and I am stuck in this. I am calling functions in a function like so:
submit = () => {
this.props.getValue();
this.props.resetValidation();
this.notify();
this.props.toggle();
this.props.disable();
this.props.actionCost();
//this.props.action();
// this.props.actionTable();
};
What is happening is that all the functions are running simultaneously without a function getting fully executed. Why is this happening shouldnt a function be called only after first function runs successfully?
Also how do I run the functions one after the other after a function is fully executed?
Please help
Upvotes: 1
Views: 2879
Reputation: 7304
The only way to stop the execution flow, is by using async/await
or a generoator
function, and even these are only "syntactic sugar" on top of Promise
.
You are probably calling an asynchronous function, and expecting it to "complete" without using await
.
Another situation is calling a function that internally using asynchronous calls (Like axios
or fetch
), and reply back with callbacks. In this situation the execution continues, and the callback will be called later, that's way we call them "callback"
For example:
console.log('before');
setTimeout(() => console.log('timer completed'), 1000);
console.log('after');
Will result in:
before
after
timer completed
In this example I'm logging before
, then setting a timeout where I'm providing a callback (a simple function) that will be executed later (1 sec.), meanwhile the execution flow continues, and logs after
. once the timer reached the system will execute my callback.
In case that you want to execute the after
after the timer completed
, you will have to provide a callback that will be called after the execution is done.
like this:
function logTimer(doAfter) {
setTimeout(() => {
console.log('timer completed');
doAfter();
}, 1000);
}
console.log('before');
logTimer(() => console.log('after'));
Upvotes: 1