Published November 17, 2023 by

Asynchronous programming in JavaScript

 Asynchronous programming in JavaScript is a programming paradigm that allows you to execute code non-blockingly In a synchronous program, each operation blocks the execution of the program until it's completed, but in an asynchronous program, operations can be initiated and continue executing without waiting for the completion of the previous ones. This is crucial for tasks that may take some time, like fetching data from a server or reading a file.

Here are some key concepts and examples to help you understand asynchronous programming in JavaScript:

1. Callbacks:

Callbacks are functions that are passed as arguments to other functions. They are executed after the completion of a particular task. Callbacks are a fundamental building block of asynchronous JavaScript.

javascript
// Callback function example
function fetchData(callback) {
    // Simulate fetching data after 2 seconds
    setTimeout(function() {
      console.log("Data fetched!");
      callback();
    }, 2000);
}

console.log("Start fetching data...");
// Invoking fetchData with a callback
fetchData(function() {
    console.log("Data fetching completed!");
});
console.log("Doing other work while data is being fetched...");

Explanation:

  • The fetchData function takes a callback function as an argument.
  • The program starts fetching data and immediately moves on to the next line without waiting for the data to be fetched.
  • After 2 seconds, the data is fetched, and the callback function is executed, printing "Data fetching completed!".
  • The last line is executed after the data is being fetched.

Expected Output:

Start fetching data...
Doing other work while data is being fetched...
Data fetched!
Data fetching completed!

2. Promises:

Promises provide a cleaner way to handle asynchronous code compared to callbacks. A Promise represents a value that might be available now, or in the future, or never.

javascript
// Promise example
function fetchData() {
    return new Promise(function(resolve, reject) {
      // Simulate fetching data after 2 seconds
      setTimeout(function() {
        console.log("Data fetched!");
        resolve(); }, 2000);
      });
}
console.log("Start fetching data...");
// Using promises with .then() and .catch()
fetchData() .then(function() {
      console.log("Data fetching completed!");
}).catch(function(error) {
      console.error("Error:", error);
});
console.log("Doing other work while data is being fetched...");

Explanation:

  • The fetchData function returns a Promise, representing the asynchronous operation of fetching data.
  • The program starts fetching data and immediately moves on to the next line without waiting for the data to be fetched.
  • The .then() method is used to handle the successful completion of the promise, printing "Data fetching completed!".
  • The .catch() method is used to handle errors, though there are none in this example.
  • The last line is executed after the data is being fetched.

Expected Output:


Start fetching data...
Doing other work while data is being fetched...
Data fetched!
Data fetching completed!


3. Async/Await:

Async/await is a more recent addition to JavaScript that makes asynchronous code look and behave more like synchronous code. It's built on top of promises.


javascript
// Async/Await example
function fetchData() {
    return new Promise(function(resolve) {
      // Simulate fetching data after 2 seconds
      setTimeout(function() {
        console.log("Data fetched!");
        resolve(); }, 2000);
      });
}
// Async function using await
async function fetchDataAsync() {
    console.log("Start fetching data...");
    await fetchData();
    console.log("Data fetching completed!");
}
// Invoking the async function
fetchDataAsync();

Explanation:

  • The fetchData function returns a Promise, representing the asynchronous operation of fetching data.
  • The fetchDataAsync function is an async function that uses the await keyword to pause execution until the promise is resolved.
  • The program starts fetching data and immediately moves on to the next line without waiting for the data to be fetched.
  • The async function is invoked, and it logs "Start fetching data...", then it awaits the completion of fetchData().
  • After 2 seconds, the data is fetched, and it logs "Data fetched!" and "Data fetching completed!".
  • The last line is executed after the data is being fetched.

Expected Output:


Start fetching data...
Data fetched!
Data fetching completed!


Asynchronous programming is particularly relevant in web development, where applications often need to interact with servers, handle user input, and perform other I/O operations without causing delays in the user interface. Embracing asynchronous patterns empowers developers to build more responsive and scalable applications in the ever-evolving landscape of web development.