Chain Array Of Promises With Bluebird
Solution 1:
Note: As adeneo pointed out in the comments, use promises only if you are dealing with asynchronous code.
Create an array of functions which are to be executed. And make sure that they all return a Promise.
Then, you can use
Promise.reduce
to reduce the initial value to the transformed final value by returning the result of executing current promise returning function, on every iteration.Finally you can attach a
then
handler to get the actual value and acatch
handler, just in case if the promises are rejected.
Lets say we have two transform functions like this.
Note: I am telling again. You should never use Promises with functions like these. You should use promises only when the functions you are dealing with are really asynchronous.
// Just add a property called `c` to all the objects and return a Promise object
function transform1(data) {
return Promise.resolve(data.map(function(currentObject) {
currentObject.c = currentObject.a + currentObject.b;
return currentObject;
}));
}
// Just add a property called `d` to all the objects and return a Promise object
function transform2(data) {
return Promise.resolve(data.map(function(currentObject) {
currentObject.d = currentObject.a + currentObject.b + currentObject.c;
return currentObject;
}));
}
Then you can transform the original value, like this
Promise.reduce([transform1, transform2], function (result, currentFunction) {
return currentFunction(result);
}, [{a: 1, b: 2}, {a: 3, b: 4}]) // Initial value
.then(function (transformedData) {
console.log(transformedData);
})
.catch(function (err) {
console.error(err);
});
Output
[ { a: 1, b: 2, c: 3, d: 6 }, { a: 3, b: 4, c: 7, d: 14 } ]
Solution 2:
You can chain Promises the way you always do: using .then()
.
Let's say you have these two transformations:
function increment(x) {
return Promise.resolve(x + 1);
}
function double(x) {
return Promise.resolve(2 * x);
}
In a real scenario, these would be doing asynchronous work. You could just:
increment(1).then(double)
But, you don't know the order or number of transformations. Let's put them into an array, and then()
them one by one:
var transformations = [increment, double]
var promise = Promise.resolve(1);
for (var i = 0; i < transformations.length; i++)
promise = promise.then(transformations[i]);
You can attach a catch()
handler before you start, after you finish or even per-transformation.
This isn't efficient if you're going to apply hundreds of transformations. In that case, you should use reduce()
as thefourtheye suggests in his answer.
Post a Comment for "Chain Array Of Promises With Bluebird"