I'm developing a search algorithm which searches through 3 databases and prints out the results. The general structure of the code looks something like this:
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(){
// Do some actions on <type>_search_results_full lists
}
Those <type>_search_results_full will be a list that contains the full list of matches for the search_string. I'd like to then wait for all of those lists to be populated, then run them through another method getFinalDisplayResults which chooses a total of X number of results to display from those full lists.
The issue I'm facing is that this.getFinalDisplayResults() executes before those <type>_search_results_full lists are full. I tried putting everything in the for loop in a separate method getFullResults() and then doing something like this:
async getFinalDisplayResults(){
await getFullResults()
// Do something
}
But that seems to not work, as adding some logs shows that the for-loop in getFullResults() finishes without the lists being populated.
I don't have a strong understanding of toPromise() and asynchronous methods, so I'm sure I'm just approaching this incorrectly. Can someone help me understand what I should be doing instead?
Promise.allis what you're looking for.