Search code examples
javascriptpromisebluebird

Bluebird promises - how to explode an array, then map it?


If I have an array:

['one.html','two.html','three.html']

how could I explode that array, apply a chain of promises to it, then combine it back together again? At the moment my code is like this:

Promise.map(['one','two','three'], function(i) {
    dbQuery('SELECT ' + i);
}).then(function(results) {
    // This has an array of DB query results
});

I'm imagining something like:

Promise.map(['one','two','three'], function(i) {
    dbQuery('SELECT ' + i);
})
.explode()
.then(function(result) {
    // Individual result
})
.combine()
.then(function(results) {
    // Now they're back as an array
});

Now, I know Bluebird doesn't have these functions, so I'm wondering what the correct Promise-y way is of doing this?


Solution

  • You can use a chain of maps:

    Promise.map(['one','two','three'], function(i) {
        return dbQuery('SELECT ' + i);
    }).map(function(result) {
        // Individual result
    }).map(function(result) {
        // Individual result
    }).map(function(result) {
        // Individual result
    }).then(function(results) {
        // Now they're back as an array
    });
    

    However the above will not be as concurrent as

    Promise.map(['one','two','three'], function(i) {
        return dbQuery('SELECT ' + i).then(function(result) {
            // Individual result
        }).then(function(result) {
            // Individual result
        }).then(function(result) {
            // Individual result
        })
    }).then(function(results) {
        // Now they're back as an array
    });