I'm trying to write a simple function that converts node-style callback functions to promises, so I can use them with async/await.
Current code:
function toPromise(ctx, func, ...args) {
let newPromise;
args.push((err, res) => {
newPromise = new Promise((resolve, reject)=> {
if(err) reject(err);
else{
resolve(res)
};
});
});
func.apply(ctx, args);
return newPromise;
}
example usage:
const match = await toPromise(user, user.comparePassword, password);
//trying to avoid the following:
user.comparePassword(password, (err, res) => {
... });
This probably doesn't make any sense with some great libraries out there, but I'm just trying to code this as an exercise.
Problem is of course match evaluates to undefined, and apparently the promise gets resolved after the await syntax line.
Any idea how I can resolve this issue?