Web Analytics

JavaScript Promises

Advanced ~25 min read

What is a Promise?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

Creating a Promise

A Promise is created using the new Promise() constructor, which takes a function (executor) with two arguments: resolve and reject.

HTML
CSS
JS

Chaining Promises

The then() method returns a new Promise, allowing you to chain multiple asynchronous operations.

HTML
CSS
JS

Promise.all()

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.

HTML
CSS
JS

Summary

  • Promises provide a cleaner way to handle asynchronous operations than callbacks.
  • Use resolve() for success and reject() for failure.
  • Use then() to handle success and catch() to handle errors.
  • Promise.all() waits for multiple promises to complete.

Quick Quiz

Which method is used to handle a rejected Promise?

A
then()
B
finally()
C
catch()
D
reject()