2013-04-05 30 views
1
的NodeJS进出口

使用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; 
     } 
    }); 
} 

我只想运行函数传递给我从数据库中获取正确的结果(其他检查将在以后的会议日期等附加)。我将如何做到这一点?

回答

2

要延迟调用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(); 
} 
// ... 
+0

这出色的作品,! – nenne 2013-04-06 07:51:03

0

除非我不完全理解你的问题,不能你只是做这样的事?

if (result && some_validator(result)) { 
    callback(); 
} 
相关问题