I need to execute a bunch of asynchronous methods (client SQLite database), and call only one final callback.
Of course, the ugly way is:
execAll : f
Promises can help manage this. There are two general scenarios - parallel and serial. Parallel can be accomplished using Promise.all(), serial is more complex - task B can only start when task A is done. Here's a bare-bones sample:
// returns a promise that resolves as the task is done
const wrap = (fn, delay) => new Promise(resolve => setTimeout(_ => resolve(fn()), delay));
const task = (fn, delay) => delay ? wrap(fn, delay) : Promise.resolve(fn());
// given a list of promises, execute them one by one.
const sequence = async l => l.reduce(async (a, b) => [].concat(await a, await b));
const tasks = [
task(_ => console.log("hello world")),
task(_ => console.log("hello future"), 1000)
];
sequence(tasks).then(_ => console.log("all done"));
You may need some ES6/7 translation to make this work in browsers or older node versions.