Javascript

Difference Between Promise and Async Await in Javascript

Promises

A promise is an object which represents the eventual completion either rejection of an asynchronous operation. Promise has methods like .then(), .catch(), and finally () to handle the asynchronous results or errors

Example of the Promise

function fetchData() {

return new Promise((resolve, reject) => {

setTimeout(()=> {
resolve(“Data fetched successfully!”);
}, 2000);

});

}
fetchData()
.then(data=> console.log(data))
.cath(error = > console.error(error))

Code Explanation Line by Line

function fetchData() {
Here I have created a function named fetchData.
I Create this function to simulate the asynchronous operations and fetch data from the server.

return new Promise((resolve, reject) => {

The fetchData function returns a new promise.
A Promise is an object used to handle asynchronous operations. It can be either resolved or rejected.

In Javascript, the new keyword is used to create an instance of an object. When we write new Promise(), we are creating a new instance of the Promise class which is a built-in feature of javascript.

The Promise object is a constructor function that is used to create a new promise.

In the above code the resolve and reject functions play critical roles in determining the outcome of the Promise. These two functions are provided by the JavaScript runtime when the Promise is created, and they are used to control the promise’s state and its eventual result.

setTimeout(() => {
resolve(‘Data fetched successfully!’);
}, 2000);

Uses setTimeout() to simulate a delay (e.g., 2 seconds) before completing the operation.
setTimeout() is accepting the callback function.

  • The resolve function is called with the string 'Data fetched successfully!'.
  • This signals the successful completion of the Promise.

Note – But resolve will be executed after two seconds.

fetchData()

  • Calls the fetchData() function, which returns a Promise.
  • The returned Promise is handled using .then() and .catch()

.then(data => console.log(data))

  • .then() method runs if the Promise is resolved.
  • In this case, it logs the resolved value ('Data fetched successfully!') to the console.

.catch(error => console.error(error));

  • catch() method runs if the Promise is rejected.
  • In this example, there is no reject call in the Promise, so this branch won’t execute. If you added an error, like:  reject(‘Error occurred!’);

The cath() block would handle it by logging ‘Error occurred!’

Async/Await

async/await is syntactic sugar introduced in ES2017 (ES8) that simplifies working with Promises, making asynchronous code look and behave more like synchronous code.

  • async: Declares a function that returns a Promise.
  • await: Pauses the execution of an async function until the Promise is resolved or rejected.

Example of the Async/Await

async function fetchData() {
try {
const data = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘Data fetched successfully!’);
}, 2000);
});
console.log(data); // Handle success
} catch (error) {
console.error(error); // Handle error
}
}

fetchData();

Related Posts

Frontend Interview Question And Answers

Question I have an array to find the duplicate value and their Index also const arr = [10, 5, 8, 8, 5, 10, 6, 5, 2, 3] Answer…