Search code examples
node.jspromisebluebird

node bluebird promise chaining


I'm new to promise. I am trying to use promise to send queries to mysql db. After some queries I will use the result from the query, do some calculations and then use the output as some parameters of next query. Looks like the following:

firstQuery(). then(secondQuery). then(thirdQuery). then(fourthQuery). ...

Say, in the fourthQuery, I need to use results coming from firstQuery and secondQuery, and will have some additional calculations. How should I do that?

I know I can get the result from the previous promise by passing a parameter to the function:

then(thirdQuery). then(cal("I can only get output from thirdQuery here")). then(fourthQuery("pass output from cal"))

In this case, I don't any advantages of Promise over callbacks, because I can always write a function to simplify the repeated callbacks.


Solution

  • If you can rewrite firstQuery, secondQuery etc you can do something like this

    function firstQuery(allResult = {}) {
        return doTheQuery()
        .then(result => {
            allResult.first = result;
            return result;
        });
    }
    function secondQuery(allResult = {}) {
        return doTheQuery()
        .then(result => {
            allResult.second = result;
            return result;
        });
    }
    function thirdQuery(allResult = {}) {
        return doTheQuery()
        .then(result => {
            allResult.third = result;
            return result;
        });
    }
    function fourthQuery(allResult = {}) {
        return doTheQuery(allRessult.first, allResult.second)
        .then(result => {
            allResult.fourth = result;
            return result;
        });
    }
    

    then you can write use

    firstQuery()
    .then(secondQuery)
    .then(thirdQuery)
    .then(fourthQuery)
    .then ...
    

    the final result will be an object with the values of all the queries in {first, second, third, fourth} properties

    Of course, if you want just the fourth query result

    firstQuery()
    .then(secondQuery)
    .then(thirdQuery)
    .then(fourthQuery)
    .then(result => result.fourth)
    .then ...