2016-06-23 114 views
0

我在寫一個小應用程序,它將用戶和鏈接存儲在json文件中。完成後的成功消息jsonfile npm

var response = saveUser(user,steamLink); 
    sendMessages(channelID,[response]); 

基本上我可以寫入文件,我只需要設置消息變量,只要它完成。

 function saveUser(userId, steamProfile,channelID){ 
     var userList; 
     var message; 
     var file = "db/db.json"; 
     var obj = JSON.parse(fs.readFileSync(file,'utf8')); 
     var userList = obj; 
     if(_.find(userList.users,['userId',userId])){ 
      message = 'This user allready has a steamlink'; 
     }else{ 
      var temp = new Object(); 
      temp['userId'] = userId; 
      temp['steamLink'] = steamProfile;  
      userList.users.push(temp); 
      var obj = userList; 
      jsonfile.writeFile(file,obj,function(err,message){ 
      if(!err){ 
      message = "Member Added"; 
      } 
      }); 
      console.log(transfer); 
     } 
     return message; 
     } 

打擾我的縮進,我似乎無法粘貼它格式化的方式!

回答

0

你的方法應該是異步的也:

function saveUser(userId, steamProfile,channelID, callback) { 
    ... 
    jsonfile.writeFile(file,obj,function(err,message) { 
     if(!err){ 
      message = "Member Added"; 
      callback(message); 
     } 
    } 
    ... 
} 

而在地方,在那裏它被稱爲來自:

saveUser(userId, steamProfile, channelID, function (message) { 
    console.log(message); 
});