With the following JavaScript pattern we can provide Promise based API to every legacy callback based function in Node.js.
import { promisify } from 'util';
const action = function (param1, callback) {
if (!callback) return promisify(checkPortStatus, arguments);
...
};
Now we can call our function with
// Before:
action(123, () => { });
// After:
await action(123);
I have to mention that we have to be careful when using optional parameters. In that case you have to check the callback function before re-invoking the function itself again.
I would argue that using the options object pattern is a good way to avoid this problem anyway.
const action = function (param1, optionalParam2, callback) {
if (typeof callback === 'undefined') callback = optionalParam2;
if (!callback) return promisify(checkPortStatus, arguments);
...
};
Aso remember, we can only use the arguments
object within a function statement / declaration / expression and NOT in a arrow function expression / lambda expression.