2 ms·
A Promise/async/await implementation of 'async.auto' is trivial, as you can use the behavior of promises themselves to avoid solving the graph: async functio
by phs2501 10y ago
A Promise/async/await implementation of 'async.auto' is trivial, as you can use the behavior of promises themselves to avoid solving the graph:
async function Promise_auto(tasks) {
const keys = Object.keys(tasks);
const results = { };
const taskPromises = { };
function runTask(key) {
if (!taskPromises[key]) {
taskPromises[key] = (async () => {
let fn = tasks[key];
if (fn instanceof Array) {
const deps = fn.slice(0, -1);
fn = fn.slice(-1)[0];
await Promise.all(deps.map(runTask));
}
results[key] = await fn(results);
})();
}
return taskPromises[key];
}
await Promise.all(keys.map(runTask));
return results;
}
Usage example (terms intentionally out of order):
(async () => {
const start = new Date();
const results = await Promise_auto({
write_file: ['get_data', 'make_folder', async (results) => {
console.log('in write_file', results);
await Promise.delay(1000);
return 'filename';
}],
email_link: ['write_file', async (results) => {
console.log('in email_link', results);
await Promise.delay(1000);
return {file: results.write_file, email: 'user@example.com'};
}],
get_data: async () => {
console.log('in get_data');
await Promise.delay(1000);
return [ 'data', 'converted to array' ];
},
make_folder: async () => {
console.log('in make_folder');
await Promise.delay(900);
return 'folder';
},
});
console.log('results = ', results);
console.log(`It took ${(new Date() - start) / 1000} seconds`);
})();