DEV Community

vimuth
vimuth

Posted on

JavaScript "async/await" and Promises.

In the evolving landscape of JavaScript, understanding the nuances between async/await and Promises is crucial for crafting efficient asynchronous code. Both offer powerful ways to handle operations that don't complete instantly, yet they differ in syntax and usage, each with its own set of advantages.

In this post we are discussing about the async/await and Promises in really simple manner.

First here is async / await.

async function waitForPizzaAndEat() {
  const message = await orderPizza(); // This waits until the orderPizza promise resolves
  console.log(message); // This waits for the above line to complete
}

waitForPizzaAndEat();
console.log('I am getting ready to eat pizza.'); // This does not wait for waitForPizzaAndEat to complete
Enter fullscreen mode Exit fullscreen mode

Check on the console log saying "I am getting ready to eat pizza." It is out of the function waitForPizzaAndEat. And there is no wait to tell browser to wait until waitForPizzaAndEat ends before running that console.log.

For scenarios like that we can use Promises. Here is how to do it.

async function waitForPizzaAndEat() {
  const message = await orderPizza(); // This waits until the orderPizza promise resolves
  console.log(message); // This waits for the above line to complete
}

// Call waitForPizzaAndEat and then log the message
waitForPizzaAndEat().then(() => {
  console.log('I am getting ready to eat pizza.'); // This will now wait for waitForPizzaAndEat to complete
});
Enter fullscreen mode Exit fullscreen mode

By attaching a .then() to the waitForPizzaAndEat call, you ensure that "I am getting ready to eat pizza." is logged only after waitForPizzaAndEat has finished executing.

Function declared with async automatically returns a Promise. That promise will resolve with whatever the function returns, or reject if the function throws an error.

And we can uses promises more efficiently like this

function waitForPizzaAndEat() {
  return new Promise((resolve, reject) => {
    orderPizza()
      .then(message => {
        console.log(message); // Log the message when the pizza order is successful
        resolve('I am getting ready to eat pizza.'); // Resolve the promise with this message
      })
      .catch(error => {
        reject(error); // If there's an error ordering pizza, reject the promise
      });
  });
}

// Using the function
waitForPizzaAndEat()
  .then(message => {
    console.log(message); // This logs "I am getting ready to eat pizza." after the above promise resolves
  })
  .catch(error => {
    console.error('Failed to eat pizza:', error); // Handles any errors
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)