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?

4

2 回答 2

1

这是正在发生的事情:

// 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
}

我添加了一些注释,什么时候发生的。如您所见,由于 node.js 的异步特性,您在从数据库中获取结果之前返回值。

您需要熟悉异步流和回调函数。

将回调函数传递给findModifier并等待数据库返回结果。

于 2013-06-07T12:13:42.107 回答
0

modifierModel.find异步运行,可能findModifier方法在 find 方法的回调执行之前返回。尽管您看到它被打印出来,但无论如何从该方法返回的内容都是空字符串。您可以使用async 之类的库。

于 2013-06-07T05:52:44.250 回答