I have a number of functions that are written to accept two callbacks and some parameters that I would like to Promisify. Example:
function myFunction(successCallback, failureCallback, someParam)
Given the above function how would I Promisify both the successCallback
and failureCallback
using a Promise library such as Bluebird?
I have tried this but it returns undefined
:
const myFunctionAsync = Promise.promisify(myFunction);
console.log(await myFunctionAsync('someParam')); // undefined
A working but overly verbose solution:
const myFunctionAsync = new Promise((resolve, reject) =>
myFunction(success => resolve(success), failure => reject(failure))
);
console.log(await myFunctionAsync('someParam')); // success
I'm looking for a way to convert these awkward multiple callback functions into Promises without wrapping each one.
Many thanks.
You could write your own version of a promisify function, that would take that function signature into account:
function myFunction(successCallback, failureCallback, someParam) {
setTimeout(_ => successCallback('ok:' + someParam), 100);
}
function myPromisify(f) {
return function(...args) {
return new Promise( (resolve, reject) => f(resolve, reject, ...args) );
}
}
async function test() {
const myFunctionAsync = myPromisify(myFunction);
console.log(await myFunctionAsync('someParam')); // success
}
test();