How do you convert a callback-based API to a promise?
You wrap the call in a promise, and then you resolve or reject inside the callback. The function that builds the promise receives the two functions that control it, so the result of the callback API becomes the result of the promise.
// Wrap a callback-style function in a promise.
function delay(ms, value) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(value);
}, ms);
});
}
delay(50, 'done').then(function (value) {
console.log(value);
});
// The same thing written with the callback API.
function delayCallback(ms, value, callback) {
setTimeout(function () {
callback(null, value);
}, ms);
}
delayCallback(50, 'done too', function (err, value) {
if (err) {
console.log('failed:', err.message);
return;
}
console.log(value);
});
Notice the shape of the error-first callback. The error is the first argument and the value is the second, and a null error means that the work succeeded. The promise wrapper turns that around. You call resolve with the value when things work, and you call reject with an error when they fail. That change is what makes promises easier to read, because a successful path has to be stated out loud instead of being implied by the absence of an error.
There is a general version of this that is worth writing once and then reusing. The promisify helper takes a function that follows the error-first rule and gives you back a function that returns a promise. It works for any number of arguments, because the extra arguments are placed before the callback.
There are two cautions to keep in mind. The callback must be called exactly once, because a promise can only settle one time. And if the underlying API can throw straight away, you should put the call inside a try block and reject from the catch block, otherwise the promise will wait forever instead of failing.