I'm a working my way with promises and I'm stuck with my use case. I have an array of transformer functions (each function is a promise and modifies some JSON structure).
Let me show some code.
Lets say this is my JSON structure (array)
var data = [{a: 1, b:2}, {a:3, b:4}];
transformFunction
is definition of transform functions modifying the data a certain way. The two functions adds c
and d
property to the above JSON structure:
var transformFunctions = { //
transform1: function (data) { // This function adds `c` property to each object from `a`
return new Promise(function (resolve) {
for (var i = 0; i < data.length; i++) {
data[i].c = data[i].a;
}
return resolve(data);
})
},
transform2: function (data) { // This function adds `d` property to each object from `c`
return new Promise(function (resolve) {
for (var i = 0; i < data.length; i++) {
data[i].d = data[i].c;
}
return resolve(data);
})
},
...
}
The from a UI user specifies which transformer functions he should use and in what order. Lets say he picked the normal order like this:
var userTransformList = ['transform1', 'transform2'];
The transform1
method should modify the data and the result should be passed to transform2
method.
I was looking at: Promise.all
but it seems that it does not care for the order of the promises, and most important it needs to pass the previous result to the next promise.
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.
Then you can transform the original value, like this
Output