函数返回undefined而不是true/false
Function returns undefined instead of true/false
我使用lazy
模块解析一个具有用户id的文件,并检查其中是否有特定用户。modCheck应该返回true/false,但它返回undefined。
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;
}
});
}
从外观上看,您的函数"modCheck"。。不是"isMod"。。。在其内部循环/foreach之前正在终止/结束。
在这种情况下,不能执行简单的返回值。。由于它将在到达返回值之前到达modCheck函数的最后一行。。。
当您返回true/false时,您应该在此时调用一个函数,该函数将处理true/false事件。。。
如果需要,可以向您展示示例,但只需将您的"return"行更改为更类似于"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');
}
}
一旦函数使用异步处理块(如lazy
部分),就不可能将其转换回同步调用(即向调用方"返回"某些内容)。
您唯一能做的就是接受一个或两个带闭包的额外参数来调用结果或错误,换句话说,您还需要发布一个异步接口。
例如,Node.js提供了一个readFileSync
,因为只给定readFile
是不可能构建的。
相关文章:
- JavaScript-切换“;全部检查”;复选框true/false
- true==false以某种方式计算为true
- Javascript似乎在说true ==false
- JavaScript onkeydown, return true,false
- 从异步函数返回true/false以用于同步if()
- 函数返回undefined而不是true/false
- 为什么true/true是1,true/false是无穷大,false/true是0,false/false是NaN
- 检查对象数组是否包含布尔值true/false
- 函数:根据字符串中是否存在子字符串返回 True/False
- 如何将 ng-show 与控制器中返回 true/false 的函数一起使用
- 在input.checked=true/false _without_ jQuery上触发一个事件
- jQuery javascript未正确返回true/false
- 如何从嵌套的jquery回调函数中返回true/false
- 如何在骨干模型属性中设置布尔值true/false
- 如何使用angular或javascript在基于true/false返回的html中显示值
- 基于true/false变量显示/隐藏进度条
- Node.js在返回true/false时停止函数
- 是否可以将true/false值传递给ajax函数
- 根据Webix中的复选框值编辑true/false
- Meteor:设置车把变量true/false