I'm trying to simplify Promise chains as much as possible by having a function handle an array of functions. They need to be in order, but my method of giving them the proper syntax isn't working, and I'm sure there's a better way to be doing this. Each function in the chain calls the database and needs to trigger the next function when it returns.
// Run each in order.
var Chain = function(chain, cb){
chain.forEach(function(i){ i = function(r){return new Promise(i)}; });
chain.reduce(function(cur, next) { {cur.then(next)} }, Promise.resolve()).then(function() { cb() });
}
Chain([
r=>{
UserData('elle', i=>{
console.log(i);
r(i)
})
},
r=>{
UserData('tyler', {age:"22"}, i=>{
console.log(i);
r(i);
})
},
r=>{
UserData('nerd', i=>{
console.log(i);
r(i)
})
},
r=>{
UserData('jeax', i=>{
console.log(i);
r(i)
})
}
], function(){
console.log("Done.");
});
The example below works how I need it, just not using the Chain function that i desire with the simplicity of each item.
var PChain = function(cb){
// Convert each item.
return function(){ return new Promise(r=>{cb(r)}) };
}
// The items.
var chain = [
PChain(r=>{
UserData('elle', i=>{
console.log(i);r(i)
})
}),
PChain(r=>{
UserData('tyler', {age:"22"}, i=>{
console.log(i);r(i);
})
}),
PChain(r=>{
UserData('nerd',
i=>{ console.log(i);r(i)
})
}),
PChain(r=>{
UserData('jeax',
i=>{ console.log(i);r(i)
})
})
];
chain.reduce(function(cur, next) { return cur.then(next) }, Promise.resolve()).then(function() {
//all executed
console.log("Done.");
});