Promising to Callback
I’ve never been a big fan of Promises for async code. That’s not a point against Promises as a concept per se; it’s more an issue of environment. Very few environments/libraries/frameworks using JavaScript use Promises; most, like XMLHttpRequest in browsers and node, use callbacks, and in order to have consistent async code you kind of have to choose one way or the other. Either you use callbacks everywhere, or you wrap all your callbacks in Promises, or you can have an inconsistent mess, but the last one isn’t really an option. What can you do about it?
Enter Promisify
This is a quick ES6 module you can drop into your project in order to take a node-style function with an errback (a function with the signature (err, data)
in its callback) and turn it into a Promise. Simply feed it the function you want to convert and the arguments you want to pass in, and it’ll return you a Promise that you can .then
, .catch
, or await
(if you’re using ES7 features in 6to5 :)). See below:
|
|
Save it as promisify.js
in your project. Then you can use it like so:
|
|
With Promises in the ES6 spec, and with ES7 building on Promises with async functions/await, expect to see more APIs use them. They may not be as fast as raw callbacks, but over time they will make your code neater as these new features go more mainstream.