Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Promisify a function that has multiple callback parameters?

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.

like image 363
Robula Avatar asked Nov 01 '25 09:11

Robula


1 Answers

Bluebird or otherwise, it's not that hard to promisify functions. Your solution is overly verbose. Try:

const myFunctionAsync = (...a) => new Promise((r, e) => myFunction(r, e, ...a));

Yeah, this is wrapping each one, but with one line per function, unless your functions all follow some pattern and you have them in array, it's not that big a deal. I.e. you're assuming additional args are at the end rather than the beginning.

like image 191
jib Avatar answered Nov 04 '25 00:11

jib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!