DEV Community

Mohamed Zurfudeen
Mohamed Zurfudeen

Posted on

Asynchronous JavaScript

Asynchronous programming is a key concept in JavaScript. It allows you to perform operations that take time to complete (like fetching data from a server) without blocking the main thread of execution. In this article, we'll explore how to write asynchronous JavaScript code using callbacks, promises, and async/await.

Callbacks

Callbacks are a common way to write asynchronous JavaScript code. A callback is a function that is passed as an argument to another function and is executed when the first function has completed its task. Here's an example:

function fetchData(callback) {
  setTimeout(() => {
    const data = { id: 1, name: 'Mohamed Zurfudeen' };
    callback(data);
  }, 2000);
}

fetchData(data => {
  console.log(data); // logs { id: 1, name: 'Mohamed Zurfudeen' }
});

Enter fullscreen mode Exit fullscreen mode

Here, we've defined a 'fetchData' function that simulates fetching data from a server by using the 'setTimeout' function. The 'fetchData' function takes a callback function as an argument, which it calls with the fetched data when it's done. We then call 'fetchData' with a callback function that logs the fetched data to the console.

Promises

Promises are a newer feature in JavaScript that provide a cleaner and more structured way to write asynchronous code. A promise is an object that represents the eventual completion (or failure) of an asynchronous operation. Here's an example:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { id: 1, name: 'Mohamed Zurfudeen' };
      resolve(data);
    }, 2000);
  });
}

fetchData()
  .then(data => {
    console.log(data); // logs { id: 1, name: 'Mohamed Zurfudeen' }
  })
  .catch(error => {
    console.error(error);
  });

Enter fullscreen mode Exit fullscreen mode

Here, we've defined a 'fetchData' function that returns a promise. Inside the promise, we use the 'resolve' function to pass the fetched data to the 'then' method when it's done, or the 'reject' function to pass an error to the 'catch' method if something goes wrong. We then call 'fetchData' and use the 'then' and 'catch' methods to handle the result or error respectively.

Async/await

Async/await is a newer and more convenient way to write asynchronous code in JavaScript. It allows you to write code that looks synchronous, but is actually asynchronous under the hood. Here's an example:

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { id: 1, name: 'Mohamed Zurfudeen' };
      resolve(data);
    }, 2000);
  });
}

async function main() {
  try {
    const data = await fetchData();
    console.log(data); // logs { id: 1, name: 'Mohamed Zurfudeen' }
  } catch (error) {
    console.error(error);
  }
}

main();

Enter fullscreen mode Exit fullscreen mode

Here, we've defined a 'main' function that is marked as 'async'. Inside the function, we use the 'await' keyword to wait for the 'fetchData' promise to resolve or reject, and assign the result to the 'data' variable. We then log the fetched data to the console or handle the error if something goes wrong.

Conclusion

Asynchronous programming is a fundamental concept in JavaScript. By using callbacks, promises, and async/await, you can write code that can perform time-consuming tasks without blocking the main thread of execution.

Top comments (0)