Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

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?

Answer №1

It seems like I understand the goal you are trying to achieve and the problem you're facing. The function this.getFinalDisplayResults() is being executed before the results are available because the logic inside the for loop is asynchronous. To resolve this issue, you can make the following adjustment:

async function getDataFromBackend () {
    for(let type in ["player", "team", "event"]) {
        const searchResult = await this.searchService.getSearchResult(type).toPromise()
        if(type === "player")
            this.player_search_results_full = this.getPlayerSearchResults(searchResult, search_string);
           
        if(type === "team")
             this.team_search_results_full = this.getTeamSearchResults(searchResult, search_string);
           
        if(type === "event")
             this.event_search_results_full = this.getEventSearchResults(searchResult, search_string);  
     }
}

  

async function getFinalDisplayResults() {
            await getDataFromBackend(); // By doing this, you ensure that data is available before proceeding with the remaining process
    //Add the rest of the logic here
}

Answer №2

It appears that you may be searching for Promise.all, which will accept an array of Promises and return an array of results upon resolution.

For your specific scenario, a potential implementation could look like this:

const results = await Promise.all(["player", "team", "event"].map( type => 
   this.searchService.getSearchResult(type).toPromise()
))

Answer №3

One way to improve the code is by iterating through an array of different types and their corresponding methods.

const promises = [
  { type: 'player', method: 'getPlayerSearchResults'},
  { type: 'team', method: 'getTeamSearchResults'},
  { type: 'event', method: 'getEventSearchResults'}
].map(obj => {
  return this.searchService.getSearchResult(obj.type).toPromise().then(search_result => {
    return this[obj.method].bind(this)(search_result, search_string);
  })
});
return Promise.all(promises);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to transfer HTML code from a textarea to CKEDITOR for setData?

My goal is to retrieve data from a textarea element and use it as setData for CKEDITOR. However, instead of receiving the HTML code, I am only getting the code as a string, which is not rendering properly as HTML. Here's the code snippet: CKEDITOR.re ...

Duplicate a Google Sheet and save it to a specific folder in Google Drive

I currently have two spreadsheets in my possession. The first spreadsheet consists of raw data that includes unique employee numbers and the names of the employees. The second spreadsheet is the one I aim to duplicate to a designated Google Drive folder. M ...

Node.JS executes Sandbox within a RESTful service environment

Utilizing the Node Restify Module to develop a REST service that accepts POST requests. Inside the service, I am attempting to create a Sandboxed process using the Node Sandbox module in order to execute dynamically inserted JavaScript without impacting th ...

What could be causing this highchart plot to fail to display in both IE and Chrome?

Check out the plot in this jsfiddle: http://jsfiddle.net/essennsee/y5HCm/ The plot looks good in Firefox, but only shows the legend in IE and Chrome. If I remove the following code snippet it works fine. Is there a different way to format the labels?: ...

What could be causing the div to be wider than the content inside of it?

I am having an issue creating a webpage with a 20-60-20 flex fill layout. The div in the center, which should occupy 60% of the page, is wider than its content, causing it to appear off-center. https://i.stack.imgur.com/WwCJy.png Here is my home.componen ...

How can I determine if a user has reached the end of a non-scrollable div by utilizing HostListener and directives within Angular?

In my Angular project, I have designed a main layout using flex display with specific height and overflow settings. The main content div inside this layout has its own unique styling to ensure consistent appearance for any components inserted within it. By ...

What could be causing my second ajax call to render the page unresponsive?

I am encountering an issue with my AJAX call. It works fine on the first attempt, but when I try to call it a second time, the page becomes unresponsive. I am not sure what is causing this issue. The code is located within the document ready function. The ...

NPM Messer - the innovative chat tool for Facebook Messenger. Ready to see it in action?

Previously, I had the idea of creating my own Messenger client. However, when I reviewed the documentation, it only provided instructions on how to write a chatbot. Despite this obstacle, I stumbled upon something intriguing - a Messer command line client. ...

Preventing the use of the <select> tag in JavaScript

As a beginner in JavaScript, I thought it would be a great idea to work on a simple Calculator project. I've already tackled the basics like addition and subtraction, but now I'm contemplating adding a squareroot function to it. The design incl ...

A guide on implementing listings in React Native through the use of loops

I am trying to display the data retrieved from an API, but I am encountering an error. // Retrieving the data. componentWillMount() { tokenner() .then(responseJson => { const token = "Bearer " + responseJson.result.token; ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

Should URL parameters be avoided as a method for retrieving data with React Router in a React application?

Within my application, there exists a main page labeled Home that contains a subpage named Posts. The routing structure is as follows: <Route path='/' element={<Home />} /> <Route path='/posts/popular' element={<Post ...

experiencing difficulty in transmitting HTML content through nodemailer

I'm having trouble sending HTML-formatted text in emails using nodemailer. exports.send = function(req, res) { console.log(req.query); var mailOptions = { to: req.query.email, subject: req.query.sub, text: 'Date of Interview: ' ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

Guide to aligning the orientation of an object with a given normal vector using three.js

Imagine I have a car object where the z-rotation is positioned to face the direction it's moving in. This car is situated on an inclined ground represented by a normalized normal vector (nx, ny, nz). How can I rotate the car's x and y axes so th ...

Implement a unique feature for specific days using jQuery UI Datepicker with a customized class

Looking to highlight a range of days horizontally in jQuery UI Datepicker with the multiselect plugin. To achieve this, I am utilizing the :before and :after pseudoelements of the a tags. .ui-state-highlight a:before, .ui-state-highlight a:after { con ...

Organize information within a single column of a table according to the heading using Angular

I have been working on implementing a sorting operation in a table for one or multiple columns. Consider the following table: When clicking on Heading 1, only Data 1 and Data 2 should be sorted. When clicking on Heading 2, Data 3 and Data 4 need to be sor ...

What is the best way to access a JSON Array in php without using any specified keys?

I'm dealing with a JSON object created in JavaScript and passed to PHP via AJAX. The issue I'm facing is that I can't figure out how to assign keys to each JSON object within the JSON array. Here's an example of how the JSON array looks ...