DEV Community

Ankit Kumar
Ankit Kumar

Posted on

JS Asynchronous-Technical Paper

Callbacks

a callback function is a function that is passed as an argument to another function and is intended to be called later, often after an asynchronous operation or a certain event occurs. Callbacks are a fundamental concept in JavaScript for handling asynchronous code execution.
Example:-

function fetchData(callback) {
  setTimeout(() => {
    const data = 'Sample data';
    callback(data);
  }, 2000);
}

function processData(data) {
  console.log('Processing data:', data);
}

console.log('Start');
fetchData(processData);
console.log('End');
Enter fullscreen mode Exit fullscreen mode

Promises

Promises are a feature introduced in ECMAScript 2015 (ES6) that provide a more structured and readable way to handle asynchronous operations in JavaScript. Promises represent the eventual completion (or failure) of an asynchronous operation and allow you to chain multiple asynchronous operations together.
Example:-

    function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = 'Sample data';
      resolve(data); // Resolving the promise with the fetched data
      // If there's an error, you can reject the promise instead:
      // reject(new Error('Failed to fetch data'));
    }, 2000);
  });
}

function processData(data) {
  console.log('Processing data:', data);
}

console.log('Start');
fetchData()
  .then(processData)
  .catch(error => {
    console.error('Error:', error.message);
  })
  .finally(() => {
    console.log('Cleanup');
  });
console.log('End');
Enter fullscreen mode Exit fullscreen mode

Here's how the execution flows:

  1. "Start" is logged to the console.
  2. The fetchData function is called, and a new Promise is created.
  3. The asynchronous operation starts with a timer set for 2000 milliseconds.
  4. "End" is logged to the console.
  5. After 2000 milliseconds, the timer expires, and the promise is resolved with the fetched data.
  6. The then method is called on the promise, and the processData function is passed as the callback.
  7. The processData function is called with the fetched data.
  8. "Processing data: Sample data" is logged to the console.
  9. The finally method is called, and "Cleanup" is logged to the console.

Code Control

the event loop plays a crucial role in managing the control flow of asynchronous code execution. It ensures that tasks, including callbacks and events, are executed in a specific order while keeping the JavaScript runtime single-threaded.
The event loop follows a cycle that consists of the following phases:

  1. Handle Synchronous Code: The event loop starts by executing any synchronous code present in the call stack. This includes executing functions, operations, and statements that are not asynchronous.

  2. Handle Asynchronous Operations: After the synchronous code is executed, the event loop checks if there are any asynchronous operations that have completed.

  • If there are completed asynchronous operations, their associated callbacks or promises are added to the callback queue or microtask queue (depending on the type of task).

  • The callbacks or promises in the queues are not executed immediately; they are waiting for the call stack to be empty.

  1. Event Loop Iteration: If the call stack is empty, the event loop starts iterating to handle the callbacks and promises waiting in the queues.
  • The event loop checks the microtask queue first. Microtasks generally include promise callbacks, mutation observers, or other high-priority tasks. It processes all the microtasks present in the queue until it is empty.

  • After processing all the microtasks, the event loop moves to the callback queue and starts executing the callbacks. These could be timer callbacks, event handlers, or other lower-priority tasks. It takes one callback from the queue and executes it.

  • The event loop repeats this process, continuously checking and executing tasks from the microtask queue and the callback queue in an alternating manner.

References

W3SCHOOL
GFG

Top comments (1)

Collapse
 
utsavdhall profile image
Utsav

Well done ankit bhai , aag laga di aapne to