Constructing an array in an asynchronous manner while simultaneously iterating through other arrays

In my attempt to create a comprehensive keyword list from the existing keywords, I successfully retrieved them all and displayed them in the debug console.

However, I am facing confusion regarding the appropriate time and method to call resolve(taxonomyKeywords). I have tried using a foreach loop, but encountered the same issue. Is my approach completely off track, or is there a simpler solution that I am missing?

private searchKeyword(searchTerm: string, results: ITag[]) : ITag[] | Promise<ITag[]>
{
  return new Promise<IPersonaProps[]>( (resolve, reject) => {
    let taxonomyKeywords : ITag[] = [];

    this.props.taxonomyProvider.getTermStores().then( (stores: ITermStore[]) => {
      for(var store of stores )
      {
        this.props.taxonomyProvider.getTermGroups( store.id ).then( (groups: ITermGroup[]) => {

          for(var group of groups)
          {
            this.props.taxonomyProvider.getTermSets(group).then( (sets: ITermSet[]) => {
              for(var termSet of sets)
              {
                this.props.taxonomyProvider.getTerms(termSet).then( (terms: ITerm[]) => {
                  for(var term of terms)
                  {
                    if( term.name.indexOf(searchTerm) >= 0 )
                    {
                      taxonomyKeywords.push( { key: term.name, name: term.name} );
}}});}});}});}});});}

Answer №1

In my opinion, the following pattern may be more efficient:

private function fetchResults(searchTerm: string, results: ITag[]): ITag[] | Promise<ITag[]> {

    return this.props.taxonomyProvider
        .getTermStores()
        .then((stores: ITermStore[]) => {
            return Promise.all(stores.map(s => this.props.taxonomyProvider.getTermGroups(s.id)));
        })
        .then((groups: Array<ITermGroup[]>) => {

            const flattenGroups: ITermGroup[] = groups.reduce((previous, current) => previous.concat(current), []);

            return Promise.all(flattenGroups.map(g => this.props.taxonomyProvider.getTermSets(g)));
        })
        .then((sets: Array<ITermSet[]>) => {
            const flattenSets: ITermSet[] = sets.reduce((previous, current) => previous.concat(current), []);

            return Promise.all(flattenSets.map(s => this.props.taxonomyProvider.fetchTerms(s)));
        })
        .then((terms: Array<ITerm[]) => {
            const flattenTerms: ITerm[] = terms.reduce((previous, current) => previous.concat(current), []);
            return flattenTerms
                .filter(term => term.name.indexOf(searchTerm) >= 0)
                .map(term => ({ key: term.name, name: term.name }));
        });
}

It is advisable to understand how promises operate.

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

Potential Scope Problem in Angular JS Controller

The HTML code snippet I have is as follows: <body ng-controller = "Control as control"> <button ng-click = "control.prepareAction()">Do Action </button> <div id="one" ng-hide = "!control.showOne" > <div> <h6> ...

Stripping /r /n tags from TinyMCE content stored in MySQL

Whenever I retrieve content from the database and display it on the screen, I notice that my output contains /r/n tags. Even though I managed to remove the slashes while handling other tags using: htmlspecialchars_decode(stripslashes($row[Content])) The ...

What are 4 different methods to tap into app closure?

Currently, I am in the process of creating regression test scripts for an express 4 application. However, when the tests are completed and the server is shutting down, an issue arises with mongodb not being closed properly. Is there a method to incorpora ...

Steps for importing vuetify/lib alongside the vuetify loader in the A-La-Carte system

When utilizing the A-La-Carte system in vuetify with vuetify-loader, I encountered a TypeScript error while trying to import vuetify/lib. I am unsure of what mistake I might be making here and would appreciate some assistance with importing this. I was re ...

What causes jquery-ui resizable to set the width of the div with the "alsoResize" property?

I have created a series of divs structured like this: <div id="body_container"> <div id="top_body"> </div> <div id="bottom_body"> </div> </div> Additionally, I have implemented the following funct ...

React Native Function fails to return a value

Within my React Native app, there's a page called RepsPage that displays a scroll view using an array of IDs. I'm passing this array to a function named renderRep, attempting to create a view for each item in the array. However, the return statem ...

Ways to remove elements from array of objects that match items in separate array of strings using javascript

In my JavaScript code, I am looking to filter an array of objects based on an array of strings. Here is the input array of objects: const input = [ { id: 1, name: 'first', type: 'first_type', }, { ...

Locate and retrieve the final character of the class identifier

I need to extract a specific class attribute value from a dynamically generated HTML element using JavaScript. The class name follows a pattern like sf-single-children-*, where the asterisk (*) represents a variable number based on the number of child elem ...

The range slider's color value is not resetting correctly when using the <input>

Before repositioning, the slider is at this location: (both thumb and color are correctly positioned) https://i.stack.imgur.com/J3EGX.png Prior to Reset: Html <input id="xyzslider" class="mdl-slider mdl-js-slider" type="range" min="0.0" max="1.0" va ...

Tips on setting up a dropzone upload feature with a click-trigger option

Is there a way to configure dropzone.js so that the file is uploaded only when a submit button is clicked, rather than automatically? Here's the code snippet I am currently using: $('#myDropzone').dropzone({ url: SITE_URL + 'self_r ...

What is the best method for transferring data stored in a Python array to an Excel file?

Currently, I am in the process of developing a python script that handles .hdf files. My goal is to extract the data and store it in an excel spreadsheet. I have successfully stored the data in an array using the following code snippet: See the code below ...

Issue with updating AngularJS model within nested ng-repeat block

My issue involves using nested ng-repeat to iterate through properties of an array of objects and connecting the model of the objects' values to inputs. The problem arises when the values inside the inputs are changed, the model fails to update. va ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

Leverage arrays as data points within Highcharts.js

I have integrated the highcharts.js library into my website to create a profit & loss chart. The values for this chart are obtained from an array that is populated through an ajax response from my server. Below is the code snippet: <script type="text/ ...

Monitor changes in a dynamic child component using Angular fire and TypeScript only (no HTML)

Currently, I am developing a component using TypeScript and passing inputs to my child component from there. In the parent TypeScript file: this.childComponent = this.viewContainerRef.createComponent(this.data.body).instance; this.childComponent['chi ...

Experiencing problems with React createContext in Typescript?

I've encountered a strange issue with React Context and Typescript that I can't seem to figure out. Check out the working example here In the provided example, everything seems to be working as intended with managing state using the useContext ...

Leveraging ng-class with multiple conditions

My goal is to assign one of three different classes to a span element based on the result of a JavaScript function. The code snippet I have written appears to be returning the correct value, but the markup always displays the 'require-matched' cl ...

Adding Options on the Fly

I am struggling with integrating option elements into optgroups within my HTML structure using JavaScript, particularly while utilizing the jQuery Mobile framework. Below is the initial HTML setup: <form> <div class="ui-field-contain"> ...

Synchronizing multiple file changes simultaneously in Node.js

I have a small development server set up specifically for writing missing translations into files. app.post('/locales/add/:language/:namespace', async (req, res) => { const { language, namespace } = req.params // Utilizing fs.promises l ...

Performing a MongoDB query in a controller using the MEAN stack with Node.js

My goal with this controller is to retrieve all the results of a collection. Despite having one item in the prop collection, I am encountering an undefined error. Error: Cannot call method 'find' of undefined This snippet shows my server.js fil ...