Skip to main content

Command Palette

Search for a command to run...

Async/Await vs Promises: How to Handle Asynchronous JavaScript

Published
1 min read
B

Backend-focused Software Engineer skilled in Node.js, Go, TypeScript, and scalable API design, dedicated to building high-performance, reliable, and efficient web systems.

Introduction:

JavaScript is asynchronous, which means certain actions (like fetching data) don’t block the rest of your code. Promises and async/await help manage these non-blocking actions.

Working with Promises:

A promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve("Data fetched!"), 2000);
  });
};

fetchData().then(data => {
  console.log(data); // Output: "Data fetched!" after 2 seconds
});

Using Async/Await:

Async/await simplifies the syntax of promises by making asynchronous code look like synchronous code.

async function getData() {
  const data = await fetchData();
  console.log(data); // Output: "Data fetched!"
}

getData();

Error Handling:

Promises handle errors using .catch(), while async/await uses try...catch.

// Using Promises
fetchData()
  .then(data => console.log(data))
  .catch(err => console.error(err));

// Using Async/Await
async function getData() {
  try {
    const data = await fetchData();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

When to Use Which:

Async/await is generally easier to read and write but works on top of promises. Promises are more flexible and are required in scenarios like parallel execution (Promise.all).

More from this blog

Codernex: Exploring Tech & Programming

9 posts

A platform where I share insights, tutorials, and expertise across a range of technologies, helping others stay informed and grow their skills.