繁体   English   中英

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

[英]How to change scope back to original function after calling a “local” function within module.exports in Node.JS

我试图在module.exports中的另一个函数“ NextMessageCalculation”中调用另一个本地函数“ MessageScoring”,但是我在使范围变回时遇到了麻烦。 该函数成功调用了另一个本地函数,但是随后更改了作用域,并且先前作用域中的变量现在都返回未定义状态。 我将如何解决此问题,或者有更好的方法来调用本地函数来避免这种情况?

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

使用提升功能,退出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
} 

暂无
暂无

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

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