gpt4 book ai didi

javascript - 将多个结果插入到express.js路由中的req对象中

转载 作者:行者123 更新时间:2023-12-03 05:47:11 27 4
gpt4 key购买 nike

我正在使用 ElasticSearch 运行 Express.js/Node.js 应用程序。我正在尝试查看同一索引中多种类型的结果。我在这里所做的是运行搜索查询,并根据查询结果执行第二个搜索查询。我还可以通过观察 node.js 控制台看到 elasticsearch 为玩家返回结果。但它们没有插入到我的结果对象/数组中。我正在使用快速中间件,因为我必须执行两个搜索并将结果显示为一个。

routes/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 。我可以显示团队数组。但玩家数组中却没有任何结果。我在这里做错了什么。

最佳答案

在您的 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);

正如 Talha Awan 所建议的,您最好不要在中间件中执行此操作,而应使用专用库,例如​​ async one (但还有很多其他的)

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);

关于javascript - 将多个结果插入到express.js路由中的req对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40292191/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com