3 ms·
As an example of non-trivial parallelism with Promises and async/await, here's a (slightly naive) implementation of Promise.auto I just whipped up. async fun
by phs2501 11y ago
As an example of non-trivial parallelism with Promises and async/await, here's a (slightly naive) implementation of Promise.auto I just whipped up.
async function Promise_auto(clauses) {
let keys = Object.keys(clauses);
let results = { };
let clausePromises = { };
function runClause(key) {
if (!clausePromises[key]) {
clausePromises[key] = (async () => {
let fn = clauses[key];
if (fn instanceof Array) {
let deps = fn.slice(0, -1);
fn = fn.slice(-1)[0];
await Promise.all(deps.map(runClause));
}
console.log('start', key);
results[key] = await fn(results);
console.log('end', key);
})();
}
return clausePromises[key];
}
await Promise.all(keys.map(runClause));
return results;
}
With the above (note clauses are intentionally out-of-order):
(async () => {
let results = await Promise_auto({
write_file: ['get_data', 'make_folder', async function(results){
console.log('in write_file', results);
return 'filename';
}],
email_link: ['write_file', async function(results){
console.log('in email_link', results);
return {'file':results.write_file, 'email':'user@example.com'};
}],
get_data: async function(){
console.log('in get_data');
return [ 'data', 'converted to array' ];
},
make_folder: async function(){
console.log('in make_folder');
return 'folder';
},
});
console.log('results = ', results);
})();
=>
start get_data
in get_data
start make_folder
in make_folder
end get_data
end make_folder
start write_file
in write_file { get_data: [ 'data', 'converted to array' ],
make_folder: 'folder' }
end write_file
start email_link
in email_link { get_data: [ 'data', 'converted to array' ],
make_folder: 'folder',
write_file: 'filename' }
end email_link
results = { get_data: [ 'data', 'converted to array' ],
make_folder: 'folder',
write_file: 'filename',
email_link: { file: 'filename', email: 'user@example.com' } }
Note that there was no topo-sorting or any other stuff to explicitly figure out an execution order, it just takes advantage of the fact that Promises can have their values pulled out multiple times to sequence things properly.