簡體   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