Skip to content

Instantly share code, notes, and snippets.

@mtorre4580
Created April 9, 2023 04:08
Show Gist options
  • Save mtorre4580/9a9f6d7f201612953ad9c90665b8872c to your computer and use it in GitHub Desktop.
Save mtorre4580/9a9f6d7f201612953ad9c90665b8872c to your computer and use it in GitHub Desktop.
Example promisify util from Node.js to convert a callback to a promise
const { promisify } = require("util");
// Example legacy callback function with schema callback(err, response)
const legacyFunctionAPI = (name, callback) => {
setTimeout(() => {
if (Math.random() < 0.5) {
callback(null, { id: 2, name });
} else {
callback(new Error("The API has fail"), null);
}
}, 1000);
};
// Convert the legacy callback to a Promise
const promiseLegacyFunctionAPI = promisify(legacyFunctionAPI);
// Example using the legacy
legacyFunctionAPI("victoria", (err, response) => {
if (err) {
console.log("Error with legacy callback", err);
} else {
console.log("Response with legacy callback", response);
}
});
// Example using the promisify helper
(async () => {
try {
const response = await promiseLegacyFunctionAPI("victoria");
console.log("Response with promise", response);
} catch (err) {
console.log("Error with promise", err);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment