1. JavaScript
  2. Advanced
  3. Promises

Promises, Promises 🤣

Last updated:

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

A Simple Promise

To replicate the asyncronous nature of a real scenario code, we’re going to use the setTimeout function to delay the flow.

const prom = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("The return string");
  }, 1000);
});

The Promise constructor takes, as parameter, a function with 2 parameters of its own: resolve and reject.

The resolve string will be passed on the then method:

prom.then(text => {
  console.log(text)
});

For the cases when a promise is rejected, a catch method is used. The third method we can use is finally which always run no matter if the promise is resolved or rejected.

setInterval(() => {
  console.log('Start:')
  const prom = new Promise((resolve, reject) => {
    setTimeout(() => {
      let rand = Math.random();
      if( rand > 0.5) {
        resolve(`Resolved: ${rand}`);
      } else {
        reject(`Rejected: ${rand}`);
      }
    }, 1000);
  });
  prom.then(text => {
    console.log(`  - then: ${text}`);
  }).catch(reason => {
    console.log(`  - catch: ${reason}`);
  }).finally(() => {
    console.log(`  - finally`);
  });
}, 2000);

Using:

  • setInterval to run the code every 2 seconds
  • Math.random() to generate a random value and resolve or reject based on it

Concurency

Scenario: loading multiple resources simultaneously but displaying them only once all are completed.

const prom1 = new Promise((resolve) => {
  setTimeout(() => {
    resolve("Resolved 1!");
  }, 1500);
});
const prom2 = new Promise((resolve) => {
  setTimeout(() => {
    resolve("Resolved 2!");
  }, 500);
});
const prom3 = new Promise((resolve) => {
  setTimeout(() => {
    resolve("Resolved 3!");
  }, 2500);
});
Promise.all([prom1, prom2, prom3])
  .then( ([text1, text2, text3]) => {
    console.log(`then: ${text1} | ${text2} | ${text3}`);
  });

then: Resolved 1! | Resolved 2! | Resolved 3! is only shown after 2.5 seconds when all promises are resolved.

Dependency

Chaining promises - that is having 2 promises that depend on each over. Eg: retrieving a list of resources and then details of a particular resource:

function firstOperation() {
  const prom = new Promise((resolve) => {
    setTimeout(() => {
      resolve("Resolved 1!");
    }, 1500);
  });
  prom.then(text => {
    console.log(` - Resolved: ${text}`)
    secondOperation();
  });
};


function secondOperation() {
  const prom = new Promise((resolve) => {
    setTimeout(() => {
      resolve("Resolved 2!");
    }, 1500);
  });
  prom.then(text => {
    console.log(` - Resolved: ${text}`)
  });
};

firstOperation();