Are basically functions that are called when some result is ready or they can also be used to signal errors.
function aDividedByB(a, b, onResultFn, onErrorFn) {
if (b != 0) {
return onResultFn(a / b);
}
return onErrorFn("The divisor can't be zero!");
}
In this example the function aDividedByB
consumes some data in the first two parameters and decides if execute the success callback called onResultFn
or call the fail callback with name onErrorFn
.
A normal call to this function would be something like
aDividedByB(6, 3, console.log, console.error);
Are a way to pipe computations where you can have a resolve
for valid results and a reject
to break the pipe with some error.
A promisify function converts some callback structured function into a Promise returning one where the success is mapped to resolve and the failure is mapped to reject.
There are many possible implementations of the promisify
function due to the different ways that callback using functions can be written. For the previous structure for aDivededByB
example, that is very common, the promisify function would be like:
function promisify(cbfn) {
return (...args) => new Promise((resolve, reject) => {
return cbfn(...args, resolve, reject);
})
}
Since we are using rest parameters we could use this to promisify any function no matter the arity as long as it accepts the success and failure callbacks in the last two parameters.
const promisedDivision = promisify(aDividedByB);
promisedDivision(6, 0)
.then(res => console.log(`Result: ${res}`))
.catch(err => console.log(`Error: ${err}`));
In this case it will enter the catch block since the reject
function was called.