What is difference between Promise and Async await in javascript

    Aug 10, 2023       by Pankaj Kumar

Both Promises and async/await are mechanisms in JavaScript for handling asynchronous operations and managing the flow of asynchronous code. They are both used to write cleaner and more readable asynchronous code, but they have slightly different syntax and behavior.

1. Promises

Promises were introduced in ECMAScript 6 (ES6) and provide a way to handle asynchronous operations in a more organized manner. A promise represents a value that may be available now, or in the future, or never. It has three states: pending, resolved (fulfilled), and rejected.

Here's how you create and use a promise:

 

 
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data fetched successfully");
    }, 1000);
  });
};
 
fetchData()
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(error);
});
 

 

2. Async/Await:

`async/await` is a syntactic feature built on top of Promises to make asynchronous code appear more like synchronous code, enhancing its readability and maintainability. An async function returns a Promise and can use the await keyword to pause execution until a Promise is resolved.

Here's how you use async/await:

 

 
const fetchData = async () => {
  try {
    const response = await new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Data fetched successfully");
      }, 1000);
    });
    console.log(response);
  } catch (error) {
    console.error(error);
  }
};
 
fetchData();
 

 

Difference between Promise and async/await:

 

1. Syntax:

  • Promises involve chaining .then() and .catch() methods.
  • async/await uses the await keyword within an async function.

 

2. Error Handling:

  • Promises use the .catch() method to handle errors in a chained manner.
  • async/await uses a try...catch block for error handling.

 

3. Readability:

  • async/await generally results in code that's easier to read and understand, especially for sequential asynchronous operations.

 

4. Flow Control:

  • async/await provides a more linear and synchronous-looking flow, as the code awaits each asynchronous operation before moving to the next line.

 

5. Error Stacks:

  • Promises may result in longer and less informative error stacks when dealing with multiple chained operations.
  • async/await provides better error stacks, making it easier to trace the source of an error.

In summary, both Promises and async/await are powerful tools for handling asynchronous operations in JavaScript. async/await is often preferred for its improved readability and error handling, but Promises are still widely used and valuable, especially in scenarios where more complex asynchronous flows or operations are needed.


WHAT'S NEW

Find other similar Articles here: