Convert Node callbacks to Promises
Node-style callbacks are the de facto standard for most server-side JS libraries. It's great to have a convention, but unfortunately, callbacks compose poorly and quickly end up in the so-called callback hell.
What are node-style callbacks? They are also called error-first callbacks, as the first argument is the error, followed by the result(s).
For example, when you read a file, you pass a function with the signature of (err, data)
:
fs.readFile("file", (err, data) => {
if (err) {
// handle error
}else {
// handle response
}
});
Since Promises are now first-class citizens, and async/await is becoming mainstream, it's better to use them for cleaner code.
But how to convert from callbacks to Promises?
1. Use a promisified library
Google around, and it's likely you'll find a promisified version of the library.
A few examples:
Instead of fs
, you can use mz.
Instead of mysqljs/mysql
, use node-mysql2.
2. Convert it manually
Simply wrap a Promise constructor around the call:
function readFile(file) {
return new Promise((res, rej) => {
fs.readFile(file, (err, data) => {
if (err) {
rej(err);
}else {
res(data);
}
});
});
}
3. Use a promisify script
Several libraries offer a script that makes a promisified version of a given function.