Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Callback issue with setTimeout()

i am new to developing raspberry pi 3 server in NodeJS. Recently i started working on NodeJS with Bluetooth BLE technology, i write a server to send response and notification over the BLE everything is working fine but when i use setTimeout() function the callback isn't work its ref become null and NodeJS isn't sent any response notification back to connected device here is my NodeJS code i am using bleno.js library for BLE Callback

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)

            }
        })
    })
}

If i moved the updateCallback(this,"1") outside setTimeout funcation then it work perfectly

like image 900
halim Sol Avatar asked Mar 19 '26 12:03

halim Sol


1 Answers

The issue seems related to the this binding in setTimeout. Either use an arrow function or use something like

const self = this before the setTimeout() and use self instead of this in setTImeout.

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)


      }
    })
  })
}
like image 66
Hemant Parashar Avatar answered Mar 21 '26 08:03

Hemant Parashar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!