DEV Community

Cover image for Async Await v/s Promises?
Pulkit Singh
Pulkit Singh

Posted on • Edited on

1

Async Await v/s Promises?

Both async/await and promises are ways to handle asynchronous code in JavaScript. They are not mutually exclusive and can be used together or independently, depending on your needs and preferences.

Async Await

Async/await is a more modern and concise syntax for working with promises. It allows you to write asynchronous code that looks and behaves like synchronous code, using the async and await keywords.

For example, with async/await, you can write code like this:

async function getData() {
  const response = await fetch('https://example.com/data');
  const data = await response.json();
  return data;
}

Enter fullscreen mode Exit fullscreen mode

Promises

Promises are a pattern for handling asynchronous operations in JavaScript. They represent the result of an asynchronous operation that may not be available yet. You can use the .then() method to specify what should happen when the promise resolves (i.e., when the asynchronous operation is completed).

For example, with promises, you can write code like this:

async function getData() {
  const response = await fetch('https://example.com/data');
  const data = await response.json();
  return data;
}

Enter fullscreen mode Exit fullscreen mode

In general, async/await can make your code easier to read and understand, especially for longer or more complex asynchronous operations. However, it's important to note that async/await is built on top of promises, so you will still need to understand how promises work in order to use async/await effectively.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
manuartero profile image
Manuel Artero Anguita 🟨

your second code box (promises) might look like this:

function getData() {
  return fetch('https://example.com/data').then(( response ) => response.json);
}

...

getData().then(jsonResponse => {  console.log(jsonResponse) })
Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️