If you have functions that return Promise s, this can be done very simply with a function like sequence :
// sequence :: [(undefined -> Promise<undefined>)] -> Promise<undefined> function sequence(fns) { var fn = fns.shift(); return fn ? fn().then(sequence.bind(null, fns)) : Promise.resolve(undefined); }
sequence assumes that your asynchronous / Promise requiring functions do not accept any inputs or produce any outputs (they are simply called for side effects.)
An example of using the sequence function:
sequence([f1, f2, f3]); function f1() { return new Promise(function (res) { setTimeout(function () { console.log('f1'); res(); }, 100); }); } function f2() { return new Promise(function (res) { setTimeout(function () { console.log('f2'); res(); }, 1100); }); } function f3() { return new Promise(function (res) { setTimeout(function () { console.log('f3'); res(); }, 10); }); }
This will lead to the exit from the mode "f1", "f2" and "f3" depending on the changing set time delays between them.
Noah freitas
source share