In the example below I need to reset some values before making the fetchData call in the fetch method. Does async await wait for all functions in the reset method to complete before continuing?
fetch = async () => {
await this.reset();
this.props.fetchData();
};
reset = () => {
this.props.resetFilter();
this.props.resetClient();
this.props.resetUser();
};
Or do you have to do something like below?
fetch = () => {
this.reset().then(() => {
this.props.fetchData();
});
};
reset = async () => {
await this.props.resetFilter();
await this.props.resetClient();
await this.props.resetUser();
};
Thanks :)
The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution. The code block below shows the use of Async Await together.
JavaScript is asynchronous in nature and does not wait for the execution of code. Therefore, it is a challenging task to wait for a piece of code before executing another piece. In this way, users prioritize the specified functions that execute first, while others are in the waiting queue.
If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.
async and awaitInside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
async
/await
does not magically deal with asynchronous function.
It is a syntax addition that allows you to easier work with promises.
So whenever a function returns a Promise, you need to wait for it explicitly.
Either by writing await
in front of each if you want to execute them in order, as you have shown in your second example:
reset = async () => {
await this.props.resetFilter();
await this.props.resetClient();
await this.props.resetUser();
};
Or if you want to allow that those asynchounous function to interleave Promise.all
:
reset = async () => {
await Promise.all([
this.props.resetFilter(),
this.props.resetClient(),
this.props.resetUser()
])
};
If you do not wait for the Promises like in your first example:
reset = () => {
this.props.resetFilter();
this.props.resetClient();
this.props.resetUser();
};
then the promise chain is broken for that three call, this might not look like be a problem at first, especially if you assume that they always resolve. But can result in an unhandled rejection if on of this promises is rejected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With