FXAMN FXAMN - 1 year ago 76
Javascript Question

Construct promise flow from json

My program has the following flow:


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


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 {


Answer Source

What you are currently doing is equivalent to

let returning = Promise.resolve(phase);

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download