了解Javascript范围麻烦

时间:2015-05-24 04:37:04

标签: javascript node.js scope

我在Node.js项目中有以下代码:

match()

var response; if (theInput == 1) { models.User.find({ usersNumber: usersNumber, active: true }, function (err, user_data) { response = "Number is 1"; }); } else if (theInput == 2) { response = "Number is 2"; } else { response = "Number is n/a"; } return response; 时,我很难设置回复。返回时响应为theInput = 1。我不想将其设置在undefined函数之外,因为我的实际响应文本(在我的实际代码中)是基于某些数据的。

1 个答案:

答案 0 :(得分:4)

response未定义,因为它是异步设置。因为输入的处理是异步的(基于回调而不是返回)。您的函数必须进行回调而不是返回值。节点中的常规做法是使用回调的第一个参数进行错误,第二个参数用于返回值:

function giveResponseForInput(theInput, callback) {
  if (theInput == 1) {
    models.User.find({
      usersNumber: usersNumber,
      active: true
    }, function(err, user_data) {
      if (err) {
        callback(err)
      } else {
        callback(null, "Number is 1");
    });
  } else if (theInput == 2) {
    callback(null, "Number is 2");
  } else {
    callback (null, "Number is n/a");
  }
}

var returnValue = giveResponseForInput(1, function(err, value) {
     console.log("callback value should be \"Number is 1\" unless the database had an error:", err ? err, value);
});

console.log("return value should be undefined", returnValue);