2015-02-06 149 views
-1

我正在使用lazy模块来解析带有用户标识的文件,并检查特定用户是否在其中。 modCheck应该返回true/false,但是它会返回undefined。函数返回undefined而不是true/false

var fs = require("fs"); 
var lazy = require("lazy"); 

function parseLineToString(line) { 
    //checks to see if line is empty 
    if (line == undefined) { 
     return ""; 
    } else { 
     return line.toString(); 
    } 
} 

function modCheck(channel, message) { 
    var readStreamMC = fs.createReadStream("channel_mods/"+getChannelID(channel)); 
    //opens a read stream to a file depending on the string "channel" 
    readStreamMC.on("end", function() { 
     //after parsing all the lines, if it hasn't returned true, return false 
     return false; 
    }); 
    //using lazy to parse all the lines in a file 
    new lazy(readStreamMC) 
     .lines 
     .forEach(function(line){ 
      //message.user is a 21 character user id 
      if (parseLineToString(line).slice(0, 21) == message.user) { 
       return true; 
      } 
     }); 
} 
+0

那些返回值只从匿名函数范围返回,而不是modCheck范围。 – 2015-02-06 22:12:51

+0

*“isMod应返回true/false,而是返回undefined”*好的。向我们展示'isMod'的代码,也许我们可以提供帮助。 – 2015-02-06 22:12:54

+1

***叹息***另一个问题和运行 – 2015-02-06 22:21:10

回答

0

通过它的外观,你的函数“modCheck”..不是“isMod”...是在其内部循环/ foreach之前终止/完成。

在这种情况下,你不能做一个简单的返回值。由于它会击中modCheck函数的最后一行它击中一个返回值之前...

当您返回真/假,你应该在这一点上调用一个函数来处理true/false事件...

如果需要,可以向你展示示例,但只需将你的“返回”行改为更像“modCheckComplete(true)”的行并具有一个称为modCheckComplete的函数,以便在返回通常会退回到调用代码的地方继续运行。

var fs = require("fs"); 
var lazy = require("lazy"); 

function parseLineToString(line) { 
    //checks to see if line is empty 
    if (line == undefined) { 
     return ""; 
    } else { 
     return line.toString(); 
    } 
} 

function modCheck(channel, message) { 
    var readStreamMC = fs.createReadStream("channel_mods/"+getChannelID(channel)); 
    //opens a read stream to a file depending on the string "channel" 
    readStreamMC.on("end", function() { 
     //after parsing all the lines, if it hasn't returned true, return false 
     modCheckComplete(false); /* CHANGED THIS */ 
    }); 
    //using lazy to parse all the lines in a file 
    new lazy(readStreamMC) 
     .lines 
     .forEach(function(line){ 
      //message.user is a 21 character user id 
      if (parseLineToString(line).slice(0, 21) == message.user) { 
       modCheckComplete(true); /* CHANGED THIS */ 
      } 
     }); 
} 

/* ADDED THIS */ 
function modCheckComplete(bResult) { 
    if (bResult==true) { 
     alert('user successful'); 
    } else { 
     alert('user failure'); 
    } 
} 
0

一旦函数使用异步处理块(如lazy部分),就不可能将其转换回同步调用(即,将“返回”给调用者)。

你可以做的唯一事情就是接受一个或两个带闭包的额外参数来调用结果或错误,换句话说你也需要发布一个异步接口。

Node.js例如提供readFileSync,因为不可能仅仅建立一个给定readFile