Javascript 函数在 nodejs 中返回未定义的值

Javascript function returning undefined value in nodejs

我正在编写获取数据的代码。 首先我调用 **getsomedata** 函数来获取数据,然后在 getsomedata 函数中调用另一个函数 getRandomdata 来获取数据并将其返回给前一个函数,但它返回 undefined。但在 getRandomdata 中可以在 console.log 中看到数据。 我需要使用 callbacks 吗?

router.get('/get-data', function (req, res, next) {
    var result = getsomedata(some_parameter);
    console.log(result);   // receiving undefined
    res.send(result);
});

function getsomedata(some_parameter_recieved) {
    var getsomedata = getRandomdata(random_params);
    console.log(getsomedata);    // receiving undefined
    return getsomedata;
}

function getRandomdata(random_params_recieved) {
    // after some calculation 
    console.log(random_data);           // receiving proper data
    return random_data;
}

Instead of return, you should use callbacks because in asynchronous operations, return does not wait for the I/O operation to complete.

Callback - 在 JavaScript 中,高阶函数可以作为函数中的参数传递。由于 JavaSCript 是单线程,一次只发生一个操作,每个将要发生的操作都在单线程中排队。这样,传递的函数(作为参数)可以在其余父函数操作(async)完成时执行,并且脚本可以在等待结果的同时继续执行。

通常这个 callback 函数作为函数的最后一个参数传入。

使用Callbacks:

router.get('/get-data', function(req, res, next) {
  getsomedata(some_parameter, function(result) {
    console.log(result);
    res.send(result);
  });
});

function getsomedata(some_parameter_recieved, callback) {
  getRandomdata(random_params, function(random_data) {
    callback(random_data);
  });
}

function getRandomdata(random_params_recieved, callback) {
  // after some calculation
  callback(random_data);
}

使用Promise:

router.get('/get-data', function(req, res, next) {
  getsomedata(some_parameter, function(result) {
    console.log(result);
    res.send(result);
  });
});

function getsomedata(some_parameter_received, callback) {
  getRandomdata(random_params).then(function(random_data) {
    callback(random_data);
  }).catch(function(e) {
    //handle error here
  });
}

function getRandomdata(random_params_received, callback) {
  return new Promise(function(resolve, reject) {
    // after some calculation
    if (RandomDataGeneratedSuccessfully) {
      resolve(random_data);
    } else {
      reject(reason);
    }
  });
}