In this example, the fact that the common callback (cb) is declared before it is used and, in my opinion, that disrupts the flow and hurts readability.
The solution to the problem may be introducing the function that will optionally call the asynchronous function, and will call the callback immediately if it isn't called. Updated example:
It should also possibly allow to pass some default value to the callback that would otherwise be retrieved from the asynchronous function, for example:
const { runIf } = require('metasync');
const { asyncFn, syncFn } = require('./localdep');
function f(a, b, callback) {
runIf(a, 'some default value', asyncFn, (err, val) => {
if (err) {
callback(err);
return;
}
// here `val` is 'some default value' if the `asyncFn()` isn't called
const result = syncFn(b, val);
callback(null, result);
});
}
We need a function that will allow to call an asynchronous function optionally, example common use case:
In this example, the fact that the common callback (
cb
) is declared before it is used and, in my opinion, that disrupts the flow and hurts readability.The solution to the problem may be introducing the function that will optionally call the asynchronous function, and will call the
callback
immediately if it isn't called. Updated example:It should also possibly allow to pass some default value to the
callback
that would otherwise be retrieved from the asynchronous function, for example:Possible implementation may look something like: