ES6: Promisifying The Native Way (with Strophe as example)
Originally published at www.melvinkoh.me.
Before ES6 provides us the native support of Promise, we rely on third-party libraries like Bluebird to enable this useful mechanism. In this post, we will see how we can promisify callback-based API in the ES6 native way and avoiding a common anti-pattern.
What is Promisify?
Promisify is to refactor conventional Callback-based API into Promise-based API.
Why to Promisify?
Traditionally, callback-based API are used to handle asynchronous function call. A callback-based API typically expects 2 arguments: onSuccessCallback, and onErrorCallback.
// Typical callback-based API
function send (message, onSuccessCallback, onErrorCallback) {
try {
// Do something with the message
} catch (error) {
onErrorCallback(error)
} onSuccessCallback()
}
If something gone wrong, the catch block will invoke the onErrorCallback() that we passed into it during function call. If everything runs without error, the onSuccessCallback() is called.
The problem of a Callback-based API is we can’t chain a series of callbacks without writing a nasty code. In some situation, there isn’t a clean way of implementing our logic without promisifying it.