Skip to main content

Command Palette

Search for a command to run...

Promises and Async-Await handling

Published
2 min read

—InitialAsync Programming

Asynchronous JavaScript allows non-blocking execution by delegating long-running tasks to the runtime environment and handling their results later through callbacks, promises, or async/await—keeping applications responsive and efficient.

console.log("Start");

setTimeout(() => {
  console.log("Async task done");
}, 2000);

console.log("End");

Promises

A promise is an object that represents the eventual result of an asynchronous operation. It is a placeholder for a value that will be available.

  1. Fulfilled—Completion state

  2. Pending - Initial state

  3. Fail - Failure state

How to Create a Promise

The basic syntax of creating a promise is

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation here
  if (/* operation successful */) {
    resolve('Success');
  } else {
    reject('Error');
  }
});

Here the promise object takes a callback, and it has two functions.

How to use Promise

In promises we have .then(), .catch() and .finally() methods

myPromise
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.error(error);
  })
  .finally(() => {
    console.log('always run');
  });

.then() runs when it is fulfilled; catch() is used to catch the error and. finally() will run always.

When you need to run multiple promises in parallel and wait for all of them to complete, Promise. all() is incredibly useful.

Async/Await

Async Await is extension of Promises, as sometimes promises can lead to Promise hell just like callback hell

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

Async
Async is a keyword used before a function to make it return a Promise automatically.

Await
Await is a keyword used inside an async function to pause execution until a Promise settles (resolves or rejects).