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();
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. Ie you're assuming additional args are at the end rather than the beginning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.