DEV Community

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

Posted on • Edited on

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.

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