Member-only story

JavaScript: Promises vs Async Await

Marika Lam
2 min readJun 20, 2024

--

What is a promise?

  • The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
  • Real Life Example, you ask for a coffee but you can’t drink that coffee yet because the waiter needs to make the coffee. The promise itself has been made, but the promise has not been resolved yet, hence you can’t get the coffee right after you ask for the coffee. You will have to wait until the response is a success or a fail.
//handle fulfilled (resolved) promises
promise.then((then) => { })

//handle failed (rejected) promises
promise.catch((error) => { });
  • then is called when the task is complete
  • catch is called when something goes wrong when processing the request
const axiosRequest = require("axios");

axiosRequest.get("https://boredapi.com/api/activity")
.then(response => {
console.log("Success!", response.data.activity);
})
.catch(error => {
console.log("Error!", error);
});

console.log("Printing this out");

//Output:
//Printing this out
//Success!
  • The reason why the console.log is printed before “Success!” is because it’s called asynchronously.

What is await?

  • The await operator is used to wait for a…

--

--

No responses yet