函数 returns 未定义,但它有值

Function returns undefined though it has value

我正在使用 nodejs。我写了一个 return 是变量的函数。当我调用该函数时,即使我尝试 return 的变量具有值,我也会得到未定义的 returned。

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;
};

它不应该 return 近似值吗? 当我打电话时,我得到 "undefined returned"

getDistance 不能是同步函数,因为它必须等待 'alert' 事件来计算 prox。另一种方法是返回 Promise,而不是立即回答:


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