简体   繁体   English

了解Javascript范围问题

[英]Understanding Javascript Scope Trouble

I have the following code in my Node.js project: 我的Node.js项目中包含以下代码:

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;

I am having a hard time setting response when theInput = 1 . theInput = 1时,我很难设置响应。 Response is undefined when it gets returned. 返回响应时undefined I don't want to set it outside of the model.find function, because my actual response text (in my real code) is based on some of that data. 我不想在model.find函数之外进行设置,因为我的实际响应文本(在我的真实代码中)是基于某些数据的。

response is undefined because it is set asynchronously . 未定义response ,因为它是异步设置的。 Because the processing of inputs is asynchronous (based on callbacks instead of returns). 因为输入的处理是异步的(基于回调而不是返回)。 Your function must take a callback rather than return a value. 您的函数必须进行回调而不是返回值。 It's also normal practice in node to use the first parameter of a callback for errors, and the second for a return value: 在节点中,也通常使用回调的第一个参数来处理错误,而第二个参数用于返回值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM