Having just discovered async JavaScript, I have been trying to conceptualize where it makes sense to use it: When about to tackle a problem, I'd like to be able to say from the start: "This is a problem where I should use async JavaScript!", and of course also the opposite.
My first thought was to start (slowly) converting everything to async for better interleave between functions. Then I realized there's tremendous overkill in such a strategy. There are plenty of functions that don't need to be asynchronous, like
var add = (a,b) => { return a+b;}
So now I'm thinking that conceptually, async JavaScript exists primarily for better I/O handling. The only other realm I can think it could be applicable to would be for long running scripts so as to not block JavaScript's single thread.
Anything/anywhere else where I should say "This is a job for async!"?
In JavaScript you can only really benefit from
async
if you plan to use an API that itself is asynchronous in nature, i.e. which can do some non-JavaScript task "under the hood" and then put a job (event) on a JavaScript job (event) queue. This job can be a callback or promise resolution.Some examples of such APIs are:
setTimeout
,setInterval
queueMicrotask
XMLHttpRequest
,fetch
requestAnimationFrame
On top of that, you should really only need
async
if your function usesawait
. Anasync
function that doesn't useawait
doesn't make much sense. Even when anawait
-less function would return a promise, then still it does not need to be declaredasync
.On the other hand, if you use some asynchronous behaviour of an API, then it is useful to promisify that API if it does not (yet) expose a promise-based API. As an example, here is a common line of code to promisify
setTimeout
:...so now in an
async
function you can introduce a "pause" of 100 milliseconds with:If you are using promises, and find your code has
.then
chains, then that is a good use case for converting to theasync
/await
syntax.