0

I am using node.js with mongoose. The problem i am facing is i am getting newModifier1 printed but outside that function the value is null.

Here is my code:

// Find userSchema

newModifier1 = "";

exports.findModifier = function(modifierName){
  modifierModel.find({'name' : modifierName},function(err,result){
    if(err){
      console.log("Error : "+err);
      throw err;
    }
    else{
      newModifier1 = result;
    //  console.log("Modifier is searched successfully : "+newModifier1);
    }
    console.log("Modifier is searched successfully1 : "+newModifier1);
  });
  // newModifier1=temp;
  return newModifier1; // it takes newModifier1 = "" value here
}

Any ideas what the problem could be?

2 Answers 2

1

This is what is happening:

// this is "global" an would be weirdly overwritten
// if function is called multiple times before finishing
newModifier1 = "";

exports.findModifier = function(modifierName){

    // TIMESTAMP: 0

    modifierModel.find({'name' : modifierName},function(err,result){

        // TIMESTAMP: 2

        if(err){
            console.log("Error : "+err);
            throw err;
        }
        else{
            newModifier1 = result;
        //  console.log("Modifier is searched successfully : "+newModifier1);
        }
        console.log("Modifier is searched successfully1 : "+newModifier1);
    });

    // TIMESTAMP: 1

    return newModifier1; // it takes newModifier1 = "" value here
}

I added some notes, when what is happening. As you can see and because of the async nature of node.js you return the value before you get a result back from the database.

You need familiarize yourself with the async flow and callback function.

Pass a callback function to findModifier and wait for the database to return a result.

Sign up to request clarification or add additional context in comments.

2 Comments

i have tried to use callback but i get error "undefined is not a function".
@user2185427 Then you did it wrong! ;-) you need to pass and additional function to the call, which you also need to as a parameter.
0

modifierModel.find runs asynchronously and probably findModifier method is returning before the callback of find method executes. Although you see it being printed out what is returned from the method is en empty string anyway. You can use a library like async.

1 Comment

can you give me async.parallel() example which is returning value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.