如何在Node.JS中的module.exports中调用“本地”函数后将范围更改回原始函数

时间:2017-05-27 20:10:50

标签: javascript node.js

我正在尝试拨打另一个本地功能' MessageScoring'在另一个函数' NextMessageCalculation'哪些都在module.exports中,但是我无法让范围更改回来。该函数成功调用另一个本地函数,但随后更改了作用域,并且前一作用域中的变量现在都返回undefined。我该如何解决这个问题,还是有更好的方法来调用本地函数来避免这种情况?

module.exports = {
   MessageScoring: function(){
    var attrs_list = Object.keys(message_attr_obj);
    var score = 0;
    for (i in attrs_list){
            if(user_data[attrs_list[i]]){
                score = score + user_data[attrs_list[i]]["beta"];
            }
            else{
                //user has no response with that attr yet so score is not added
            }
    }
    score = score / attrs_list.length;
    return score}... //returns an int

   NextMessageCalculation: function(){ //has a call to a mongodb and the logic takes place in the callback
MESSAGE_collection.find({'message_set':user_data.message_set,'id':{$nin:[1111]}}).toArray(function(err,doc){
                 if (doc.length === 0)
                   {
                        USERDATA_collection.update({phone:phone_num},{$set:{send_message:false}},function(err,res) {
                           db.close()
                        });
                   }
                    else{
                        var highest_score = "";
                        var next_message = "";
                        for (i in doc)
                        {
                            console.log(doc[i]['id']);
                           var score = module.exports.MessageScoring(doc[i].attr_list,user_data);
                           console.log(doc[i]['id']); <---- becomes undefined here after calling scoring function which correctly returns int 
                            if (highest_score === "")
                            {
                                console.log(doc[i]);
                                next_message = doc[i].id;
                                highest_score = score;
                            }
                            if (highest_score < score)
                            {
                                next_message = doc[i].id
                                highest_score = score;
                            }
                            console.log(doc[i].id);
                        }

1 个答案:

答案 0 :(得分:0)

使用函数提升,从modules.expors关闭中退出,并确保MessageScoring不会改变数据。

module.exports = {
   MessageScoring,
   NextMessageCalculation: 
}

function MessageScoring() {

}

function NextMessageCalculation(){
  const d = [{ id: 'ok' }];
  const i = 0;
  console.log(d[i]['id']); //returns ok
  var score = MessageScoring(doc[i].attr_list,user_data);
  console.log(d[i]['id']); //returns ok
}