Skip to content

Promises and async/await

In JavaScript, asynchronous operations (such as fetching data from an API, reading files, or waiting for a set timeout) can be handled in a few different ways. Promises and the async/await syntax provide modern solutions for dealing with asynchronous code.

PROMISES

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A promise object has a state that can be one of the following:

  1. Pending : Initial state, neither fulfilled nor rejected.
  2. Fulfilled : The operation completed successfully.
  3. Rejected : The operation failed.
const promise = new Promise((resolve, reject) => {
// contain an operation
// ...
// return the state
if (success) {
resolve(value);
} else {
reject(error);
}
});
promise
.then((result) => {
console.log(result); // If resolved
})
.catch((error) => {
console.log(error); // If rejected
});
  • resolve: called when the operation is successful.

  • reject: called when the operation fails.

  • .then() handles the resolved value of the Promise.

  • .catch() handles any rejection or error that occurred.

ASYNC/AWAIT

async and await are syntactic sugar that make working with Promises easier, allowing you to write asynchronous code in a more synchronous (and readable) manner.

  • async: This keyword is placed before a function to make it asynchronous. An async function always returns a Promise.
  • await: This keyword is used inside an async function to pause the execution of the function until the Promise resolves.

The await will wait for the Promise returned from the function() to settle. The await keyword can be used only inside the async functions.

async function showServiceCost() {
try {
let cost = await getServiceCost('cleaning');
console.log(`The service cost is ${cost}`);
} catch(error) {
console.log(error);
}
}
async function fetchData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();