Is possible to call async function without await keyword? and what happens if we call without await?
You only need await
if the caller needs to wait for the function to be done, for instance when it needs the result of the function, or when it needs to wait for some state/data change that the function causes. If there is no such dependency, you can just 'fire and forget', by not using the await
keyword.
As others mentioned, you could use .then
as well, but the basic rule is the same: you do that, when you have something specific to do after the function is done. It can be omitted otherwise.
So concretely: With 'caller', I simply mean the function that calls the async function. In your case that would be componentDidMount
. The options are then quite simple:
- Keep as is.
usrs()
will be run in the background completely andcomponentDidMount
will continue running until its end. - Use
await
, socomponentDidMount
will wait for the return ofusrs()
. - Use
usrs().then()
, socomponentDidMount
can continue, but the code specified in.then()
is invoked afterusrs()
returns, if you need to do something that has to happen afterusrs()
is done.
We use await
when we need to call and wait for async
function or Promise
In your case when you call it without await
inside your componentDidMount
, your function will work but your componentDidMount
will not wait for that function to completely finishes.
Also if you don't want to use await
and you don't want to wait inside componentDidMount
, but you want to get notified when your async
function finishes, you can use .then
instead. Because async
functions returns Promise
Here is your componentDidMount
with .then
Notice that in this example this.doSomethingElse
will call before the this.usrs
is complete, and you only will be notified inside .then
about your this.usrs
result when it finished:
componentDidMount(){
this.usrs(usrs).then(() => {
// Your functions completely finished
})
.catch(err => {
// There was an error
});
this.doSomethingElse();
}
The async work before the name of the function means that the function always returns a promise, so yes it is possible.
await makes JavaScript wait until the promise is resolved and it pauses when you need to work on the result of that promise.
To understand it better I recommend seeing following page https://javascript.info/async-await