What is a Promise in JavaScript?

A Promise are objects used for asynchronous operations. They represent the eventual completion or failure of an asynchronous operation and allow chaining and handling of success or error cases.

A Promise has three states:

Example of a Promise:


let myPromise = new Promise((resolve, reject) => {
    let success = true; // You can change this to false to test the rejection
        if(success) {
            resolve("Operation was successful!");
        } else {
            reject("Operation failed.");
        }
    });

myPromise
        .then(result => console.log(result))   // Success
        .catch(error => console.log(error));   // Failure