Clive Z Clive Z - 1 month ago 7
TypeScript Question

How to pass a function as parameter to Promise in TypeScript?

When trying to write a wrapper class for asynchronous DynamoDB calling, I failed with the attempt to wrap all the return statements with a function call as:

function composePromise(method: (params: any, callback: (err, res) => void) => void, params: any): Promise<any> {
return new Promise<any>((resolve, reject) =>
method(params, (err, res) => {
if (err) reject(err);
else resolve(res);
})
);
}

create(params: any): Promise<any> {
return composePromise(this._db.put, params);
}


Which is strange, because after I move the promise in
create
without any change, it works.

create(params: any): Promise<any> {
return new Promise<any>((resolve, reject) =>
this._db.put(params, (err, res) => {
if (err) reject(err);
else resolve(res);
})
);
}


So I am guessing it might be some closure issue, but cannot figure out why. Could anyone please help me with that?

Answer

I think that this._db.put is probably a shortcut to some other function declared on this._db, if so then the method is probably using this and that's where it fails.

You should bind the correct context to that function

create(params: any): Promise<any> {
    return composePromise(this._db.put.bind(this._db), params);
}