我正在使用ElasticSearch运行Express.js / Node.js应用程序。我正在尝试查看同一索引中多种类型的结果。我在这里执行的是运行搜索查询,然后根据查询结果执行第二个搜索查询。通过观察node.js控制台,我还可以看到elasticsearch为玩家返回了结果。但是它们没有插入到我的结果对象/数组中。我使用快速中间件,因为我必须执行两个搜索并将结果显示为一个。
路线/index.js
function searchTeam(req, res, next){ searchModuleTeams.searchTeams(req.body, function(data) { req.teams = data; next(); }); } function searchPlayer(req, res, next){ //req.players = []; req.teams.forEach(function(team){ req.body = {searchTerm:team._source.shortName}; searchModulePlayers.searchPlayers(req.body, function(data){ req.players.push(data); console.log(req.players); }); }); next(); } function renderResults(req, res){ res.render('index',{ title:'Search Teams and Players', teams:req.teams, players:req.players }); } router.post('/search-tp',searchTeam, searchPlayer, renderResults);
我通过阅读post1和post2提出了这个解决方案。我可以显示teams数组。但是什么都不来自玩家数组。我在这里做错了什么。
在searchPlayer函数中,next()应将调用放置在所调用的回调函数中searchPlayers(),基本上与您对该searchTeam()函数所做的完全相同。
searchPlayer
next()
searchPlayers()
searchTeam()
function searchTeam(req, res, next){ searchModuleTeams.searchTeams(req.body, function(data) { req.teams = data; next(); }); } function searchPlayer(req, res, next){ req.players = []; <--- uncomment this... req.teams.forEach(function(team){ req.body = {searchTerm:team._source.shortName}; searchModulePlayers.searchPlayers(req.body, function(data){ req.players.push(data); <--- ...otherwise this will fail next(); <--- move next() here }); }); } function renderResults(req, res){ res.render('index',{ title:'Search Teams and Players', teams:req.teams, players:req.players }); } router.post('/search-tp',searchTeam, searchPlayer, renderResults);
而且,正如TalhaAwan所建议的那样,您最好不要在中间件中执行此操作,而应使用专用的库,例如async一个(但还有很多)
async
import waterfall from 'async/waterfall'; function searchTeam(callback){ searchModuleTeams.searchTeams(req.body, function(teams) { callback(null, teams); }); } function searchPlayer(teams, callback){ let teamPlayers = []; async.each(teams, function(team, teamCallback) { let search = {searchTerm: team._source.shortName}; searchModulePlayers.searchPlayers(search, function(players){ teamPlayers.push(players); teamCallback(); }); }, function(err) { callback(err, teams, teamPlayers); }); } function renderResults(req, res){ async.waterfall([ searchTeam, searchPlayer ], function (err, teams, players) { res.render('index',{ title:'Search Teams and Players', teams: teams, players: players }); }); } router.post('/search-tp', renderResults);