Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Manage Asynchronous Operations with Promises and Async/Await in JavaScript

1 min read .
Manage Asynchronous Operations with Promises and Async/Await in JavaScript

Promises represent values that may become available later. async and await provide syntax for working with promises using control flow that resembles synchronous code.

Create a Promise

function callFirstName() {
  return new Promise((resolve) => {
    setTimeout(() => resolve('John'), 1000);
  });
}

A promise can be fulfilled with resolve or rejected with reject.

Await a Promise

async function fullName() {
  const first = await callFirstName();
  return `${first} Doe`;
}

An async function always returns a promise. await pauses only that async function until the awaited promise settles; it does not block the JavaScript runtime’s entire event loop.

Run Independent Work Concurrently

If two operations do not depend on each other, start them before awaiting both:

async function fullName() {
  const firstPromise = callFirstName();
  const lastPromise = callLastName();

  const [first, last] = await Promise.all([firstPromise, lastPromise]);
  return `${first} ${last}`;
}

Awaiting one before starting the other would make independent operations run sequentially.

Handle Rejections

async function load() {
  try {
    const value = await operation();
    console.log(value);
  } catch (error) {
    console.error('Operation failed:', error);
  }
}

Reject with Error objects rather than plain strings when possible because they carry useful stack and message information.

Conclusion

Promises model asynchronous results, while async/await makes promise-based workflows easier to read. Start independent work concurrently, handle rejection paths deliberately, and remember that async functions themselves return promises.

chevron-up