【问题标题】:how do I exit (return) from a function inside a another function如何从另一个函数中的函数退出(返回)
【发布时间】:2022-01-26 00:33:31
【问题描述】:

我这样做是为了在文件中保存一些信息并使用 readline 节点模块逐行读取

有两个 res.send() 一个是 return 。它只在当前函数内返回它所在的位置。如何完全退出 then 函数?

这只是为了测试。我知道我应该使用数据库

router.post('/login', (req, res) => {

    console.log(req.body);
    var lineReader = require('readline').createInterface({
        input: require('fs').createReadStream('./users.txt')
    });

    lineReader.on('line', function (line) {
        const lineJson = JSON.parse(line);

        if (lineJson["username"] == req.body.username) {
            if (lineJson["password"] == req.body.password) {


                return res.send({ msg: "matched" });
            }
        }
    })

res.send({msg:"not matched"});
})

简化

function(){
    function(){

        return...
    }
}

【问题讨论】:

  • 错误是什么?我认为它正在工作
  • 问题是,在 on() 处理程序被触发之前,外部函数可能已经返回。所以你在这里尝试做的事情是不可能的。您也许可以将 lineReader 的流包装到 Promise 中并从路由处理程序中等待它。
  • 不能从外部函数返回。您可以做的是将内部函数包装到将在特定条件下解析的 Promise 中,然后等待该函数结束。在这种特殊情况下,您还需要处理“关闭”事件(即,如果未找到用户名/密码)。
  • on() 是同步的。我试试看。

标签: javascript node.js


【解决方案1】:

您的问题与您对 nodejs 的异步特性的体验有关。

您需要使用async mode 中的行阅读器进行测试:

lineReader.eachLine('file.txt', function(line, last, cb) {
  console.log(line);

  if (/* done */) {
    cb(false); // stop reading
  } else {
    cb();
  }
});

或者只是read the entire file,然后像查询sql表一样查询:

var table = //some asyn read of file

if(user-password match){
  return res.send({ msg: "matched" });
}else{
  return res.send({msg:"not matched"});
}

您还可以在异步模式下读取文件(更好)并在回调中执行您的快速逻辑

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2020-06-12
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多