[英]Callback becomes null after being passed as function parameter
I have 2 functions funcA
and funcB
. 我有2个功能
funcA
和funcB
。 funcA
calls funcB
and passes a callback. funcA
调用funcB
并传递一个回调。 In funcA
the callback ( cb
) is well-defined, but funcB
gets undefined
. 在
funcA
,回调( cb
)是定义明确的,而funcB
是undefined
。
Here is the code: 这是代码:
MyClass.prototype.funcA= function (a) {
return new Promise((resolve, reject) => {
let cb = (reading) => {
console.log("Will resolve:" + reading);
resolve(funcC(reading));
};
if (cb)
console.log("cb ok");
else
console.log("cb ko");
this.funcB(a, cb);
});
}
MyClass.prototype.funcB= function (a, callback, c) {
console.log("funcB");
console.log("callback: " + callback);
this.device.send(a, response => {
console.log("CB ?");
if (callback) {
console.log("CB !");
callback(response);
}
else {
console.log("no callback");
console.log(callback);
}
});
if (c) {
funcB([0x00, 0x00]);
}
};
And here is the console output: 这是控制台输出:
cb ok
funcB
callback: (reading) => {
console.log("Will resolve:" + reading);
resolve(funcC(reading));
}
CB ?
no callback
undefined
Note that in the code base I have other functions that calls funcB
and funcB
successfully calls the callback. 请注意,在代码库中,我还有其他调用
funcB
函数,而funcB
成功调用了回调。
I've found the issue. 我发现了问题。
this.device.send()
does not call the callback it is given, but the callback given in a previous call. this.device.send()
不会调用给定的回调,而是上一次调用中给定的回调。 As it was not documented I had to go 3 layers down to find the implementation... 因为没有记录,所以我必须向下三层才能找到实现...
So the solution is to call funcB()
until the callback you want is called. 因此解决方案是调用
funcB()
直到调用funcB()
的回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.