函数返回undefined而不是true/false

Function returns undefined instead of true/false

本文关键字:true false 返回 undefined 函数      更新时间:2023-09-26

我使用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是不可能构建的。