3

I have the following code in my Node.js project:

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. Response is undefined when it gets returned. 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.

1
  • 1
    I assume models.User.find is an asynchronous call, which means your callback function will not execute immediately. Your return call executes before your callback. Commented May 24, 2015 at 4:45

1 Answer 1

4

response is undefined because it is set asynchronously. 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.