下面的代码工作正常:
useEffect(() => {
const apiService = new APIClient('api address');
var topicCommentsReq = new GetTopicDetailsRequest();
topicCommentsReq.setTopicCid(Buffer.from("123", "hex"));
apiService.getTopicDetails(topicCommentsReq, {}, function (err, response) {
console.log(`response : ${JSON.stringify(response)}`);
});
}
我想把这个回调风格的函数转换成async/await风格,所以我做了如下的事情:
const promisifyFn =
(fn: Function) =>
(...args: any[]) =>
new Promise((resolve, reject) => {
return fn(...args, (err: Error, data: any) => {
return err ? reject(err) : resolve(data);
});
});
useEffect(() => {
(async () => {
const apiService = new APIClient("api address");
const topicCommentsReq = new GetTopicDetailsRequest();
topicCommentsReq.setTopicCid(Buffer.from("123", "hex"));
const getTopicDetails = promisifyFn(apiService.getTopicDetails);
try {
const res = await getTopicDetails(topicCommentsReq, {});
console.log(`response : ${JSON.stringify(res)}`);
} catch (e) {
console.log(e);
}
})();
});
显示以下错误消息:
TypeError: Cannot read properties of undefined (reading 'client_')
if (callback !== undefined) {
return this.client_.rpcCall(
this.hostname_ +
'/StelaPlatform.GRPC.API/GetTopicDetails',
request,
metadata || {},
this.methodDescriptorGetTopicDetails,
callback);
}
我猜这个问题与lcoal作用域有关。当函数在async函数中运行时,this作用域是不同的。但是我应该如何解决这个问题呢?
1条答案
按热度按时间h79rfbju1#
问题是在将函数引用传递给
apiService.getTopicDetails
时,它丢失了它的this
上下文。为了使prototype函数保持在其原型中,您应该使用箭头函数...
或Function.prototype.bind()