TIL how to convert a Callback to a Promise
POSTED ON:
TAGS: callback promises advanced
How to convert a Callback to a Promise #
Standard Callback:
function getTheThing(thingToGet, successCallback, failureCallback) {
// get the thing
const thing = someDatabaseQuery(thingToGet);
if (thing) {
// on success
successCallback(thing);
} else {
// on failure
failureCallback(thing);
}
// better version
// return (thing) ? successCallback(thing) : failureCallback(thing);
}
If we are successful, it goes to the successCallback
. If it fails, it goes to the failureCallback
.
Callback functions work well for simple asynchronous operations, but can become difficult to manage and lead to "callback hell" when dealing with more complex operations.
Why switch over to a promise?
- Nested callbacks can quickly become difficult to read and understand.
- Callback functions can be error-prone when not properly implemented, such as failing to handle errors.
- It can be difficult to know when all callbacks have completed, or to handle errors that occur during a series of callbacks.
So let's modernize it by converting a standard callback into a Promise.
function getTheThingAsync(thingToGet){
return new Promise((resolve, reject) => {
getTheThing(thingToGet => {
const thing = someDatabaseQuery(thingToGet);
if (thing) {
resolve(thing)
} else {
reject(new Error("Wasn't able to do it"))
}
})
)
}
// using the promise
getTheThingAsync()
.then(result => console.log(result))
.catch( error => console.error(error));
A Refresher on Javascript Callbacks and Promises
Related TILs
Tagged: callback