Your best bet is to go with when.settle
, settle returns all promises when they resolve, not when they fulfill so you can manually check which one did well and which one did not.
var arrayOfPromises = array.map(testMapper);
when.settle(arrayOfPromises).then(function(descriptors){
descriptors.forEach(function(d){
if(d.state === "rejected"){
// do cleanup for that promise, you can access its rejection reason here
// and do any cleanup you want
} else{
// successful results accessed here
console.log("Successful!", d.value);
}
})
});
Note:
This is actually not a small problem. When I say not a small problem, what I mean is that it's a huge problem that's really hard to solve correctly. There are multiple implied behaviors here and edge cases.
Consider reading this somewhat lengthy discussion.
If you're willing to consider - Bluebird has an experimental promise-using
branch that allows specifying disposers, which would let you do this rather easily.
You would be able to do:
using(pool.getConnectionAsync().disposer("close"), function(connection) {
return connection.queryAsync("SELECT * FROM TABLE");
}).then(function(rows) {
console.log(rows);
});
Or in the multiple resource case:
var a = Promise.cast(externalPromiseApi.getResource1()).disposer("close");
var b = Promise.cast(externalPromiseApi.getResource2()).disposer("close");
using(a, b, function(resource1, resource2) {
// once the promise returned here is resolved, we have a deterministic guarantee that
// all the resources used here have been closed.
})