【问题标题】:Pass function to next function, fire depending on condition. nodejs将函数传递给下一个函数,根据条件触发。节点
【发布时间】:2013-03-28 12:05:32
【问题描述】:

我正在使用 express.js 创建一个 node.js REST 服务器,作为其中的一部分,我还创建了一个简单的会话系统。我有 3 个模块:

  • app.js
  • highscoreMan.js
  • userSession.js

http://localhost/api/highscores 的 app.js 网址现在使用给定参数调用 userSession:

//Get all highscores
app.get('/api/highscores', function (req, res) {
  userSession.checkValidity(req.query['username'], req.query['sessionid'], highscoreMan.getAll(req, res));
});

但是,在 checkValidity 中,我传递的函数会被自动调用:

function checkValidity(username, sessionId, callback) {
  userSession.findOne({ userid: username, sessionid: sessionId }, function (err, result) {
        if (err) {
          console.log(err);
        }
        if(result) {
          callback;
        }
  });
}

我只想运行正在传递的函数,因为我从数据库中获得了正确的结果(稍后将添加其他检查以用于会话日期等)。我该怎么做?

【问题讨论】:

    标签: node.js asynchronous express


    【解决方案1】:

    要延迟调用highscoreMan.getAll(),您需要声明另一个function,以便稍后调用:

    app.get('/api/highscores', function (req, res) {
      userSession.checkValidity(req.query['username'], req.query['sessionid'], function () {
        highscoreMan.getAll(req, res);
      });
    });
    

    否则,将立即调用它,并将其 return 值传递给 userSession.checkValidity()

    请注意,您还需要调整 checkValidity 以调用传递的 callback

    // ...
    if(result) {
      callback();
    }
    // ...
    

    【讨论】:

      【解决方案2】:

      除非我不完全理解你的问题,否则你就不能这样做吗?

      if (result && some_validator(result)) {
          callback();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-03-28
        • 1970-01-01
        • 2011-07-19
        • 1970-01-01
        • 2016-08-07
        • 2023-03-17
        • 1970-01-01
        • 2015-09-16
        • 2022-10-15
        相关资源
        最近更新 更多