Javascript 带有setTimeout()的NodeJS回调问题

Javascript 带有setTimeout()的NodeJS回调问题,javascript,node.js,bluetooth-lowenergy,Javascript,Node.js,Bluetooth Lowenergy,我是在NodeJS中开发raspberry pi 3服务器的新手。最近,我开始使用蓝牙BLE技术开发NodeJS,我编写了一个服务器,通过BLE发送响应和通知,一切正常,但当我使用setTimeout()时函数回调不起作用,它的ref变为null,NodeJS没有向连接的设备发送任何响应通知这是我的NodeJS代码我正在使用bleno.js库进行回调 To send response back to the caller function updateCallback(ref, msg=""){

我是在NodeJS中开发raspberry pi 3服务器的新手。最近,我开始使用蓝牙BLE技术开发NodeJS,我编写了一个服务器,通过BLE发送响应和通知,一切正常,但当我使用setTimeout()时函数回调不起作用,它的ref变为null,NodeJS没有向连接的设备发送任何响应通知这是我的NodeJS代码我正在使用bleno.js库进行回调

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(这个“1”)移到setTimeout函数之外,那么它工作得很好

这个问题似乎与
setTimeout
中的
this
绑定有关。要么使用箭头函数,要么使用类似

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)


      }
    })
  })
}