Converting Between Callbacks and Promises
One of the basic techniques required for building things in JavaScript, is the ability to effortlessly convert between functions that use callbacks and functions that return promises.
Callback ➡ Promise
// Generic function with a callback
const exampleCallback = (firstParam, secondParam, callback) => {
try {
const data = "some really important information";
callback(null, data);
} catch (err) {
callback(err, null);
}
};
const callbackToPromise = (firstParam, secondParam) =>
new Promise((resolve, reject) => {
const callback = (err, data) => (err ? reject(err) : resolve(data));
callbackFn(firstParam, secondParam, callback);
});
Promise ➡ Callback
// Generic promise
const examplePromise = (firstParam, secondParam) =>
new Promise((resolve, reject) => {
try {
const data = "some really important information";
resolve(data);
} catch (err) {
reject(err);
}
});
const promiseToCallback = (firstParam, secondParam, callback) => {
promiseFn(firstParam, secondParam)
.then(data => callback(null, data))
.catch(err => callback(err, null));
};
Bonus: NodeJS util.promisify and util.callbackify
When converting between callback style and promises, NodeJS has a handy pair of tools specifically made for this purpose. The one thing to note is that the callback function signature is (error, data)
- util.promisify: https://nodejs.org/api/util.html#util_util_promisify_original
- util.callbackify: https://nodejs.org/api/util.html#util_util_callbackify_original
const { promisify, callbackify } = require("util");
const callbackToPromise = promisify(exampleCallback);
const promiseToCallback = callbackify(examplePromise);
Which one is best
Whichever makes your code more intelligible.
Each is a separate way of organizing the paths that your code takes. Callbacks are slightly faster and with less overhead, but the performance difference is negligible compared to the gains in readability of your code. Naturally, performance may be important in highly repetitive tasks, but coincidentally, these tasks tend to be more readable when written in the callback form.