Promise chains in JavaScript

— 5 minute read

permalink

In this article I will tell you a bit more about promise chaining. For this specific usecase I needed a promise chain in node.js but the same actually applies to vanilla js

What is a promise? permalink

Sounds pretty logical right, and it actually is. You tell the script a promise is going to end eventually.

A basic promise looks like:

let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
});

promise.then(function(data) {
console.log(data); // Returns 1
}).catch(function(error) {
console.log(error);
});

You can see we define the promise as a let in this case, it can as well be a function. The promise then gets called and the then identifies the first result. We include a catch to catch any errors in the promise (reject)

Then what is promise chaining for? permalink

You use promise chaining if you want to run code in sequences. Lets say the following example:

  1. Return default number from api
  2. Multiple that number by 2
  3. Multiple the multiplied number by 2

In a more real world example these would be api call asynchronous but waiting for each other.

This looks as following:

let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000);
});

promise.then(function (result) {
console.log(result); // 1
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function (result) {
console.log(result); // 2
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function (result) {
console.log(result); // 4
}).catch(function (error) {
console.log(error);
});

As you can see we included some timeouts in this. When you run this code you will see a 1000ms wait then log 1 then 1000 ms wait => log 2 another 1000ms wait log 4.

This is our chain of promises each promise will wait for the previous one to complete.

See below for a demo on CodePen

See the Pen Promise chain JavaScript by Chris Bongers (@rebelchris) on CodePen.

Promise chain's are a boss right? permalink

Hopefully you are as excited about promise chains as I am, feel free to send me a message on Facebook or Twitter and let me know what topics you want to read more about!