'Is await mandatory to use with async method in JavaScript
I was discussing with someone else about the use of async/await in JavaScript and we didn't agree.
Personally, I only use await when I need to wait for the async method to be finished. If I don't need it to finish to continue, I don't. E.g.:
async myAsyncMethod() {
axios.get(`/foo`)
.then((response) => {
this.foo = response.data;
}).catch (exception) {
//do something with exception
this.foo = null;
};
}
If I need the data right away, I call:
await myAsyncMethod();
If I don't, I do:
myAsyncMethod();
Is it not correct to do this last one? The other person maintained that I should not. If so, would it be possible to explain to me why.
I've edited the myAsyncMethod() to be more precise. So my questions implies that that I catch errors and that I know that 'foo' is either null either field with data at some point... The point is that I don't need those data right away and I've got other things to do that don't require it.
Solution 1:[1]
An async function without an await expression will run synchronously.
The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.
So, in your case, the myAsyncMethod will return an unsettled promise unless you await it.
References:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Victor Karangwa |
