Home Blog CV Projects Patterns Notes Book Colophon Search

Serial Promises

Let's imagine you want to fetch a user, and then make an AJAX request with their last name to find their age.

Here's an implementation of the two API calls we need:

function getUser(token) {
    return new Promise((resolve, reject) => {
        if (token === "bob") {
            resolve({firstName: "bob", lastName: "gardner"});
        } else {
            reject(new Error("Invalid token"));
        }
    });
};
function findAge(lastName) {
    return new Promise((resolve, reject) => {
        if (lastName === "gardner") {
            resolve(22);
        } else {
            reject(new Error("Invalid token"));
        }
    });
};

Here's some code to call them one after the other:

getUser("bob").then((person) => {
    return findAge(person.lastName);
}).then((age) => {
    console.log("Bob is "+age);
}).catch((err) => {
    console.log("Couldn't get Bob's age: "+err);
});

Notice the return findAge(person.lastName); line that returns a promise. This is what makes the chaining work.

By chaining all the function calls together like this the one catch() at the end of the chain will handle problems in either getUser() or findAge().

Creating an automated way to run lots of promises one after the other (a waterfall) isn't usually very useful because usually you want to do something with the result of the first promise before starting the second one. This means that any benefit you get from code that automates the processing is lost when you try to get the code to run in the right shape to fit the function. You are usually best off just chaining the promises manually as we've done here.

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.