FXAMN FXAMN - 3 months ago 8
Javascript Question

Construct promise flow from json

My program has the following flow:

Promise.resolve(phase_1)
.then(phase_2)
.then(phase_3)
.then(phase_4)
.catch(errorHandler);


But i want but the phases in a flow.json:

[
"phase_1",
"phase_2",
"phase_3",
"phase_4",
]


But achieve the same result. Is it possible?

How i'm trying to:

let returning;
flow.forEach(function(phase, index) => {
if (!index && !returning) {
returning = Promise.resolve(require(phase));
} else {
returning.then(require(phase));
}
});


Thanks!!!

Answer

What you are currently doing is equivalent to

let returning = Promise.resolve(phase);
returning.then(flow[0]);
returning.then(flow[1]);
returning.then(flow[2]);
returning.then(flow[3]);

To get the actual chaining, you'd need to do returning = returning.then(…) in your code. You can (and should) however simplify it a lot by using reduce instead of forEach (which also fixes the problem of not doing the initialisation outside of the loop):

promise = flow.reduce(function(chain, phase) {
    return chain.then(phase);
}, Promise.resolve(phase));

Notice that phase is expected to be a function here, so if flow really consists of strings you probably had to do

    return chain.then(() => doSomething(phase));
Comments