Short questions: Why is there no Promise.chain in Javascript (comparable to Promise.all)? Is my implementation o.k.?
My 'codec' behaved wrong:
- Reading a graph from a XML file
- Creating all nodes (the creation method returns a promise)
- Waiting for all node creations to finish
- Create all edges between the nodes
The problem: The order of the database calls for the node creation (Step 2) got mixed up at execution time.
Solution: I had to chain the database calls in correct order before the methods became executed.
/**
* chains a list of functions (that return promises) and executes them in the right order
* [function() {return Promise.resolve();}, function() {return Promise.resolve();}]
*
* @param funcs is an array of functions returning promises
* @returns {Promise}
*/
function chain_promises(funcs) {
if (funcs.length < 1) {
return Promise.resolve();
}
var i = 0;
return chain_executor(funcs, i);
}
/**
* Recursive help method for chain_promises
* 1) executes a function that returns a promise (no params allowed)
* 2) chains itself to the success resolve of the promise
*
* @param funcs is an array of functions returning promises
* @param i is the current working index
*/
function chain_executor(funcs, i) {
var promise = funcs[i]();
return promise.then(function(){
console.log(i);
if (funcs.length > i+1) {
return chain_executor(funcs, i+1);
} else {
return Promise.resolve();
}
})
}