Javascript function returning undefined value in nodejs

让人想犯罪 __ 提交于 2019-12-03 03:39:44

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

Callback - In JavaScript, higher order functions could be passed as parameters in functions. Since JavaSCript is a single threaded, only one operations happens at a time, each operation thats going to happen is queued in single thread. This way, passed functions(as parameter) could be executed when rest of the parent functions operation(async) is completed and script can continue executing while waiting for results.

Usually this callback function is passed in as the last argument in the function.

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

Using 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);
    }
  });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!