Search code examples
node.jsbluebird

Can anyone help me understand what is the use of .spread in Bluebird library


I'm working on my first Nodejs application, someone else has developed this application before me and I'm trying to fix some issue and having trouble understanding the following.

return Promise.join(
        findStagingAdvanced(stagingQuery),
        findDboAdvanced(dboQuery)
    )     
    .spread((stagingIssues, dboIssues) => _.concat(dboIssues, stagingIssues))
    .then(....) 

Solution

  • If you have a promise that is fulfilled with an array and that array has a known length, then you can use .spread() to convert the array to individual function arguments. It is a substitute for .then() that converts the arguments from an array to individual arguments before calling your handler.

    So, instead of this:

    someFunction().then(function(arrayOfArgs) {
        let arg1 = arrayOfArgs[0];
        let arg2 = arrayOfArgs[1];
    });
    

    You can do this:

    someFunction().spread(function(arg1, arg2) {
        // can directly access arg1 and arg2 here 
    });
    

    So, in your specific code example, Promise.join() already offers a callback that separates out the individual results so it should not be needed at all. So, you could just do this:

    return Promise.join(
            findStagingAdvanced(stagingQuery),
            findDboAdvanced(dboQuery),
            (stagingIssues, dboIssues) => _.concat(dboIssues, stagingIssues)
        ).then(allIssues => {
            // allIssues contains combined results of both functions above
        });
    

    What this code is doing is collecting the results from findStagingAdvanced() and findDboAdvanced() and merging those results together into a single array of results.


    It could be written in standard ES6 (e.g. without Bluebird's extra capabilities) like this:

     return Promise.all([findStagingAdvanced(stagingQuery), findDboAdvanced(dboQuery)])
       .then(results => results[0].concat(results[1]))
       .then(allIssues => {
            // allIssues contains combined results of both functions above
        });