Finally async/await will be supported in all major browser soon except IE.
So now we can start writing more readable code with async/<
For those asking how you extend this to a run-time determined number of calls, you can use 2 loops. The first starts all the tasks, the second waits for everything to finish
console.clear();
function wait(ms, data) {
return new Promise( resolve => setTimeout(resolve.bind(this, data), ms) );
}
/**
* While here we call the functions first,
* then wait for the result later, so
* this will finish in 500ms.
*/
async function runTasks(timings) {
let tasks = [];
for (let i in timings) {
tasks.push(wait(timings[i], `Result of task ${i}`));
}
/* Want fast fail? use Promise.All */
//return Promise.All(tasks);
let results = [];
for (let task of tasks) {
results.push(await task);
}
return results;
}
async function taskRunner(fn, arg, label) {
const startTime = performance.now();
console.log(`Task ${label} starting...`);
let result = await fn(arg);
console.log(`Task ${label} finished in ${ Number.parseInt(performance.now() - startTime) } miliseconds with,`, result);
}
void taskRunner(runTasks, [50,100,200,60,500], 'Task List');