0

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"

sakib11
  • 496
  • 1
  • 5
  • 20
  • 2
    You order a pizza, you hang up the phone, and you try to eat it.... Welcome to the world of asynchronous programming. The code does not magically sit around and wait for `echo.on('alert'` to execute. – epascarello May 03 '19 at 17:06
  • 1
    https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello May 03 '19 at 17:07
  • Can I make it not **asynchronous**?. @epascarello. Like is there any way I can make it a blocking method ? – sakib11 May 03 '19 at 17:13
  • That is what the callback is for. – epascarello May 03 '19 at 17:15
  • 1
    See also my post: [JavaScript: How (not) to get a value “out of” a callback](https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html) – Felix Kling May 03 '19 at 17:28

1 Answers1

1

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();


arkeros
  • 177
  • 3
  • so I did some digging from the thread youve posted and seems like await wouldnot work in my case but the then result is perfect. Thanks so much. – sakib11 May 03 '19 at 17:47