Home Blog CV Projects Patterns Notes Book Colophon Search

Promise Trees

Let's imagine you want to do something more complicated.

Say you are a shop selling coats and umbrellas. You have access to a weather API, and a stock check system. You want to know whether you should order more coats and umbrellas or if you already have enough.

Here are our sample API calls:

function getWeather() {
    return Promise.resolve({
        temperature: 8,
        rainChance: 0.5,
    });
};
function getUmbrellaCount() {
    return Promise.resolve(10);
};
function getCoatCount() {
    return Promise.resolve(5);
};

Here's the code:

const weather = getWeather()
const coatCount = weather.then((weather) => {
    if (weather.temperature < 10) {
        return getCoatCount();
    }
    return Promise.resolve(null);
});
const umbrellaCount = weather.then((weather) => {
    if (weather.rainChance > 0.2) {
        return getUmbrellaCount();
    }
    return Promise.resolve(null);
});
Promise.all([umbrellaCount, coatCount]).then(values => { 
    console.log(values);
});

You should see:

[ 10, 5 ]

The nice thing about this is that even though coatCount and umbrellaCount both depend on the same result from the weather API, only one request is actually made and both share the result. This happens without the code that runs them both in parallel even being aware of the weather Promise.

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