Skip to content

Instantly share code, notes, and snippets.

@mattdanielbrown
Created May 25, 2024 00:17
Show Gist options
  • Save mattdanielbrown/4bddef04b60e9ad21731f84ab257d485 to your computer and use it in GitHub Desktop.
Save mattdanielbrown/4bddef04b60e9ad21731f84ab257d485 to your computer and use it in GitHub Desktop.
Javascript Asynchronous Functions : Promisified Functions (with `catch() ` )
<!-- Result is just pen's the output of
Javascript Console content in
effectively in fullscreen mode -->
function callback_BasedFunction(arg1, arg2, callback) {
// Perform asynchronous operations
// Call the callback with the result or error
setTimeout(() => {
const result = arg1 + arg2;
if (result % 2 !== 0) {
callback(null, result);
} else {
callback(new Error("Result is not odd!"), null);
}
}, 1000);
}
function promisifiedFunction(arg1, arg2) {
return new Promise((resolve, reject) => {
callback_BasedFunction(arg1, arg2, (error, result) => {
if (error) {
reject(error); // Reject the Promise with the error
} else {
resolve(result); // Resolve the Promise with the result
}
});
});
}
// Usage example:
promisifiedFunction(2, 3)
.then((result) => {
console.info(`\n\n\t\t + FIRST promisifiedFunction() was SUCCESSFUL... ( Result : ${result} )`);
})
.catch((error) => {
console.error(`\n\n\t\t - ! FIRST promisifiedFunction() FAILED... ( ERROR : ${error.message} )`);
});
promisifiedFunction(2, 4)
.then((result) => {
console.info(`\n\n\t\t + SECOND promisifiedFunction() was SUCCESSFUL... ( Result : ${result} )`);
})
.catch((error) => {
console.error(`\n\n\t\t - ! SECOND promisifiedFunction() FAILED... ( ERROR : ${error.message} )`);
});
<script src="//codepen.io/nullobject/pen/cngzI.js"></script>
<link href="//codepen.io/nullobject/pen/cngzI.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/sanitize.css/2.0.0/sanitize.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/2.0.0/modern-normalize.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment