我是在NodeJS中开发树莓派3服务器的新手。最近,我开始使用蓝牙BLE技术开发NodeJS,我编写了一个服务器来通过BLE发送响应和通知,但一切正常,但是当我使用setTimeout()函数时,回调不起作用,其ref变为null,而NodeJS不起作用已将任何响应通知发送回连接的设备,这是我的NodeJS代码,我正在使用bleno.js库进行BLE回调
To send response back to the caller
function updateCallback(ref, msg=""){
if (ref._updateValueCallback) {
console.log('Response value : '+msg);
ref._updateValueCallback(ref._value);
}
}
if(tokens[2]=="1"){
func.storeRelayAction(db, "1", decryptedString).then(result => {
this._value = Buffer.from(result.toString(), 'utf8');
updateCallback(this,result.toString()); // Send proper call back to device
}).then(()=>{
unlockTrigger();
var timer = func.getTimer(db);
timer.then(delayTime=>{
console.log(delayTime + "::delayTime");
if(delayTime){
setTimeout(function(){
lockTrigger();
console.log("after sleep");
this._value = Buffer.from("1", 'utf8');
updateCallback(this,"1");// Not Working from here
},parseInt(delayTime)*1000)
}
})
})
}
如果我将updateCallback(this,“ 1”)移出了setTimeout函数,那么它将完美地工作
答案 0 :(得分:1)
该问题似乎与this
中的setTimeout
绑定有关。使用箭头功能或使用类似的
const self = this
在setTimeout()之前,并在setTImeout中使用self
代替this
。
function updateCallback(ref, msg = "") {
if (ref._updateValueCallback) {
console.log('Response value : ' + msg);
ref._updateValueCallback(ref._value);
}
}
if (tokens[2] == "1") {
func.storeRelayAction(db, "1", decryptedString).then(result => {
this._value = Buffer.from(result.toString(), 'utf8');
updateCallback(this, result.toString()); // Send proper call back to device
}).then(() => {
unlockTrigger();
var timer = func.getTimer(db);
timer.then(delayTime => {
console.log(delayTime + "::delayTime");
if (delayTime) {
//use an arrow fn here
setTimeout( () => {
lockTrigger();
console.log("after sleep");
this._value = Buffer.from("1", 'utf8');
updateCallback(this, "1"); // Not Working from here
}, parseInt(delayTime) * 1000)
}
})
})
}