Async JavaScript and I/O

302 Views Asked by At

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!"?

2

There are 2 best solutions below

0
On BEST ANSWER

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:

On top of that, you should really only need async if your function uses await. An async function that doesn't use await doesn't make much sense. Even when an await-less function would return a promise, then still it does not need to be declared async.

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:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

...so now in an async function you can introduce a "pause" of 100 milliseconds with:

await delay(100);

If you are using promises, and find your code has .then chains, then that is a good use case for converting to the async/await syntax.

0
On

There are several usecases to make use of async logic in javascript. A common example is performing http requests. As you already pointed out, you do not want to block the scripts execution when waiting on server responses or user inputs.

JavaScript apps make strongly use of the so called promise. A promise will emit an event once it has been resolved or rejected. Another possibility is via callback function:

console.log(1)
const wait = function () {
  return setTimeout(function() {
    console.log(3)
  }, 50)
}
wait()
console.log(2)

Example using a promise:

console.log(1)
const wait = function() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, 50)
  })
}
wait().then(() => console.log(3))
console.log(2)

Hope this clarifies somehow.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise