Asynchronous JavaScript – How Web APIs and Promises Work

Asynchronous JavaScript – How Web APIs and Promises Work

Why do we need to use the Asynchronous function?

  • to avoid the block of our main thread, it give bad experience to user if browser is slow
  • if the function performs complex code that consumes good time so, to avoid thread block, we need to use
  • API hitting time we needed because we don't want our JS engine to get blocked

Default way of running code

JavaScript is a single-threaded programming language which means only one thing can happen at a time.

Single-threaded languages simplify writing code because you don’t have to worry about the how the compiler is running the code

But single-threaded programming language also means you can’t able to perform long operations such as network access, any complex query task slow down our website because it is going to block the main thread.

How to avoid main thread blocking

To resolve this issue asynchronous JavaScript come into play. Using asynchronous JavaScript (such as callbacks function like set timeout / setTimeInterval, promises, and async/await), you can perform long these solutions to hit the network requests without blocking the main thread.

Asynchronous operation in javascript

We classify asynchronous JavaScript operations mainly in two cases :

  1. Web APIs : These include methods like setTimeout, or event handlers like, mouse over, and click.
  2. Promises. A unique JavaScript object that allows us to perform asynchronous operations.

How to Handle Browser Web APIs

const printName() =>  {
  console.log('print me');
}

setTimeout(printName, 2000);

console.log('i was print first ')

The setTimeout function executes a function after nearly 2seconds . In the code above . The output would be :

  • i was print first
  • print me

*> How it happen ? ?

The answer lies in below :

promise.avif

How the Javascript Engine handle Web APIs

  • The JavaScript engine uses the stack data structure to keep track of currently executed functions. The stack is called the function execution stack. It runs code line-by-line, one-by-one.

  • When the browser/web APIs are triggered by the javascript compiler, it sends the callback functions to the web API. Thus here, the beginning asynchronous operation started. The below code keeps working. It does not stop.

  • The callback function is moved to the callback queue when the timer ends or webApi task gets completed.

  • The callback queue is getting filled by other callback functions line-wise.

  • Now it's an event loop. The job is to move the items from the callback queue to the main thread.

  • Whenever the event loop finds the main thread is empty, it moves one item of the callback queue to the main thread. Now the code of will run this way we are able to achieve the asynchronous way of running code.

How the JavaScript Engine Handles Promises

In JavaScript, promises are special objects that help you perform asynchronous operations. But the promise callback function has high priority than other asynchronous callback functions because the callback function of the promise gets to the priority queue, also called a job queue.

What is the Job Queue in JavaScript? Every time a promise occurs in the code, the executor function gets into the job queue.

The item in the callback queue is called a macro task, and the item in the job queue is also called a microtask.

Demo of the job queue


function fun1 () {
  console.log('f1')
}
function checkMicroQueue () {
  setTimeout(fun1, 0)

  new Promise((resolve, reject) => resolve('I am a promise')).then(resolve =>
    console.log(resolve)
  )
}

checkMicroQueue()

> - the output will be :

  1. I am a promise'
  2. f1