Hope you are all well. I have had this problem for quite a few months now where I am not really sure when to use async code, or on occasions, why it should be used in certain places.
I know HOW to use it, how to structure it, and where to put the async await keywords in the right places. It is more the “should I be using it now or not” or the “why is it used here” scenarios that really confuse me.
Any responses or advice would be greatly appreciated!
I might be mistaking but in my opinion async code should be used for telling the JS to not execute the function here and now when the code is running.
By default the code will be executed from top to bottom, and f.e. you want to get some data from the server and assign it to the variable. If you won’t use async you will get an error, because the data from server won’t just be there at the moment when the code is being executed.
But if you use async, you tell JS that “okay, i need this data, but you should wait till it is received and THEN please assign it to the variable”. So the code will continue executing without errors and when the async function completes it will do whatever you wanted it to do.
In my experience, usually when I am writing async functions it’s because they rely on something else that is inherently asynchronous. For example, an http call. We send a request to the api and then wait for the api to respond with the requested data. On a day to day level, async means that we’re relying on something external which will notify us when it’s done.
You certainly can make some of your code asynchronous for efficiency. If you have a process that is slow (usually because it is data intensive) you might not want to block the surrounding code from executing. Remember that if the calling function needs to consume the code synchronously, they can do so with an
The rule of thumb is, if there might be a delay in acquiring a value needed by the function (e.g. your function needs to grab something from the database, or rely on a value given by a user), that’s when you have to use async.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.