Is there anything out there already that do similar to the following.
/**
* ex.
* const ret = await asyncify(Math.max)(arg1, arg2);
*/
asyncify(func) {
return async (...inputs) => {
// wait for all inputs being resolved
const inputsResolved = await Promise.all(inputs);
return await func(...inputsResolved);
};
}
/**
* ex.
* const ret = await execute(Math.max, arg1, arg2);
*/
async execute(func, ...inputs) {
// wait for all inputs being resolved
const inputsResolved = await Promise.all(inputs);
return await func(...inputsResolved);
}
With these functions (one or the other) I can then do something asynchronous without complex code structure to make sure the tasks are executed in correct sequence and maximally in parallel.
// Task A and B can run in parallel
const retA = asyncTaskA(payloadA);
const retB = asyncTaskB(payloadB);
// Task C and D depend on A and B, but they can run in parallel as well.
const retC = asyncify(
(payloadC1, payloadC2) => {
asyncTaskC(payloadC1.someField, payloadC2.otherField);
}
)(retA, retB);
const retD = asyncify(asyncTaskD)(retA, retB);
// Task A and B can run in parallel
const retA = asyncTaskA(payloadA);
const retB = asyncTaskB(payloadB);
// Task C and D depend on A and B, but they can run in parallel as well.
const retC = execute(
(payloadC1, payloadC2) => {
asyncTaskC(payloadC1.someField, payloadC2.otherField);
},
retA,
retB
);
const retD = execute(asyncTaskD, retA, retB);
If not, is it something that worth adding to the Promise similar to Promise.all
?
const retC = Promise.asyncify(asyncTaskD)(retA, retB));
Update: adding a more complex example:
/**
* A -> B
* B -> C
* A -> D
* B,D -> E
* C,E -> F
*/
async function aComplexWorkflow() {
const A = Lib.execute(asyncTaskA);
const B = Lib.execute(asyncTaskB, A);
const C = Lib.execute(asyncTaskC, B);
const D = Lib.execute(asyncTaskD, A);
const E = Lib.execute(asyncTaskE, B, D);
const F = Lib.execute(asyncTaskF, C, E);
return F;
}