[英]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: 尝试编写用于异步DynamoDB调用的包装器类时,我尝试将所有return语句包装为带有函数调用的方式失败:
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
的诺言之后,它就起作用了。
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?
有人可以帮我吗?
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. 我认为
this._db.put
可能是在this._db
声明的某些其他函数的快捷方式,如果是这样,则该方法可能正在使用this
方法,而这就是失败的地方。
You should bind the correct context to that function 您应该将正确的上下文绑定到该函数
create(params: any): Promise<any> {
return composePromise(this._db.put.bind(this._db), params);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.