I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows:
for(type in ["player", "team", "event"]){
this.searchService.getSearchResult(type).toPromise()
.then(search_result => {
if(type == "player"){
this.player_search_results_full = this.getPlayerSearchResults(search_result, search_string);
}
if(type == "team"){
this.team_search_results_full = this.getTeamSearchResults(search_result, search_string);
}
if(type == "event"){
this.event_search_results_full = this.getEventSearchResults(search_result, search_string);
}
})
}
// this.getFinalDisplayResults()
getFinalDisplayResults(){
// Perform actions on <type>_search_results_full lists
}
The <type>_search_results_full
list will have all matching results for the search_string. I want to wait until all these lists are populated before running them through another method getFinalDisplayResults
, which selects X number of results to display from those complete lists.
The problem I'm encountering is that this.getFinalDisplayResults()
runs before the completion of <type>_search_results_full
lists. I attempted putting everything inside the for loop into a separate method getFullResults()
and then using something like this:
async getFinalDisplayResults(){
await getFullResults()
// Perform the required action
}
However, it appears not to be functioning correctly, as some logs indicate that the for-loop in getFullResults() finishes without fully populating the lists.
My knowledge of toPromise() and asynchronous methods is limited, so I believe my approach may be incorrect. Can someone provide guidance on what I should do differently?