
Below function returns a callback with an error and message.
const delay = (sec, cb) => {
if (sec > 3) {
cb(new Error(`${sec} seconds is too long. Try shorter time delay.`));
} else {
setTimeout(() => cb(null, `${sec} delay completed.`), sec)
}
}
const cbfunc = (error, message) => {
if (error) {
console.error(error.message);
} else {
console.log(message);
}
}
delay(4, cbfunc);
This is the way callbacks is used.Now let's do the same thing with util.promisify
const { promisify } = require('util');
const delay = (sec, cb) => {
if (sec > 3) {
cb(new Error(`${sec} seconds is too long. Try shorter time delay.`));
} else {
setTimeout(() => cb(null, `${sec} delay completed.`), sec)
}
}
const promiseDelay = promisify(delay); // passing function to promisify, it returns a promise
promiseDelay(2)
.then(console.log)
.catch(error => console.error(error));
The delay function remains the same way. The way the callback is used is modified with promisify.
Comments
Post a Comment