Search code examples
javascriptnode.jssocket.ioreturngpio

Function returns undefined though it has value


I am just using nodejs. I wrote a function that returns a variable. When I call that function, I get undefined returned even through the variable I am trying to return has value.

function getDistance() {
  var MICROSECDONDS_PER_CM = 1e6 / 34321;
  var trigger = new Gpio(23, { mode: Gpio.OUTPUT });
  var echo = new Gpio(18, { mode: Gpio.INPUT, alert: true });
  trigger.digitalWrite(0); // Make sure trigger is low
  var startTick;
  var prox;
  trigger.trigger(10, 1);
  echo.on('alert', (level, tick) => {
    if (level == 1) {
      startTick = tick;
    } else {
      var endTick = tick;
      var diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
      prox = diff / 2 / MICROSECDONDS_PER_CM;
      distance = prox;
      console.log(prox);
    }
  });
  return prox;
};

Shouldn't it return the prox value ? When I make a call, I get "undefined returned"


Solution

  • getDistance cannot be a synchronous function since it has to wait for an 'alert' event to compute prox. An alternative would be returning a Promise, instead of an immediate answer:

    
    function getDistance() {
      return new Promise((resolve, reject) => {
        var MICROSECDONDS_PER_CM = 1e6 / 34321;
        var trigger = new Gpio(23, { mode: Gpio.OUTPUT });
        var echo = new Gpio(18, { mode: Gpio.INPUT, alert: true });
        trigger.digitalWrite(0); // Make sure trigger is low
        var startTick;
        var prox;
        trigger.trigger(10, 1);
    
        echo.on('alert', (level, tick) => {
          if (level == 1) {
            startTick = tick;
          } else {
            var endTick = tick;
            var diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
            prox = diff / 2 / MICROSECDONDS_PER_CM;
            distance = prox;
            console.log(prox);
            resolve(prox);
          }
        });
      });
    }
    
    // Use it
    getDistance().then(result => {
      // do stuff
    });
    
    // or with syntactic sugar
    const result = await getDistance();