Promises

A Promise is an object that may produce a single value sometime in the future, either a resolves value or a reason that it's not resolved (rejected).

A Promise may in one of three possible states.

  1. pending

  2. fulfilled

  3. rejected

EX: 
const promise = new Promise((resolve, reject) => {
    if (true) {
        resolve("Stuff worked");
    } else {
        reject("Error: Something went wrong");
    }
});

promise.then(res => console.log(res)); // Stuff worked

promise
    .then(res => res + '!')
    .then(res2 => console.log(res2)); // Stuff worked!

promise
    .then(res => res + '!')
    .then(res2 => {
        throw Error('Simple error');
        console.log(res2);
    })
    .catch((err) => console.log(err)); // Simple error
    
promise
    .then(res => res + '!')
    .then(res2 => {
        return res2 + '?';
    })
    .catch((err) => console.log(err))
    .then((res3) => console.log(res3)); // Stuff worked!?

catch is executed only when any error occurred. It will considers the error only it occurred before its placement.

EX:
const promise = new Promise((resolve, reject) => {
    if (true) {
        resolve("Stuff worked");
    } else {
        reject("Error: Something went wrong");
    }
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'HIII');
});

const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, 'PROOKIE');
});

const promise4 = new Promise((resolve, reject) => {
    setTimeout(resolve, 5000, 'It is me you are loking for me?');
});

Promise.all([promise, promise2, promise3, promise4])
    .then(values => console.log(values));
// ["Stuff worked", "HIII", "PROOKIE", "It is me you are loking for me?"]

Promise all takes multiple promises in array and result will be array of all the results of all promises.

The result will be received only after all the promises execution is completed. If any one of them gets error, all process will be stopped.

Last updated