JavaScript Lessons

JavaScript Promise Tutorial: Handle Async Results

Learn how the JavaScript Promise object represents the result of an async operation. Use resolve, reject, and then to make your code easier to read.

Serhat ALPASLAN1 min read

what is a javascript class and how is it used?

 

The JavaScript Promise object is an object that represents the result of an operation, and it tells you whether an operation will happen or whether it will succeed. The Promise object is used to manage asynchronous operations and makes your code more readable.

To create a Promise object, you use new Promise(). Inside this object you place two functions that say what an operation will do. One reports the success state of the operation, and the other reports the failure state of the operation.

For example:

const pageLoad = new Promise((resolve, reject) => {
  if (pageLoadedSuccessfully) {
    resolve();
  } else {
    reject();
  }
});

In this example, if the page loads, the Promise object succeeds and runs the then() function. If the page does not load, the Promise object fails and runs the catch() function.

Promise objects can also combine multiple Promise objects. This is done with Promise.all(). You place multiple Promise objects inside this function, and once all the Promise objects succeed, a combined Promise object is created.

 

Share it if it helped

Write a comment