Tips for making sure AngularJS runs a function and its subfunction sequentially

How do I run the code below to display the details of each flavor and its corresponding ITEM ID in a specific order.

Execution Format:


Flavor1, Flavor2 -- Getflavors()
Flavor1
ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID)
GET ITEM1 DETAILS and add it to Content - GetItemID_Details(ITEM_ID, FLAVOR_ID)
GET ITEM2 DETAILS and add it to Content - GetItemID_Details(ITEM_ID, FLAVOR_ID)
Flavor2
ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID)
GET ITEM1 DETAILS and add it to Content -- GetItemID_Details(ITEM_ID, FLAVOR_ID)
GET ITEM2 DETAILS and add it to Content -- GetItemID_Details(ITEM_ID, FLAVOR_ID)
....
....
DISPLAY Content

Code:

I've seen suggestions for using callback() and promise(), but unsure how to implement them in subfunctions.


Getflavors() {
   getFlavors().then(function () // API call to fetch flavors
      Flavors = $scope.Flavors;     
      Flavors.map(function (element) {    
          GetItemIDs_ofeachFlavor(element);
      }
   })
}

function GetItemIDs_ofeachFlavor(MapFlvID) {
    getItemIDs_ofeachFlavor(MapFlvID).then(function () {    // API call to get ITEM IDs of each flavor
        ItemIDsofeachflavor = $scope.ItemIDsofeachflavor;   
        GetItemID_Details(ITEM_ID, FLAVOR_ID);
    })
}

function GetItemID_Details(ITEM_ID, FLAVOR_ID) {
     getItemDetails(ITEM_ID, FLAVOR_ID).then(function () {    // API call to fetch details of each ITEM ID
         ItemDtls = $scope.ItemDetails;
         Content = '<table style="width:100%">';
         Content += '<tr> <td> ...ItemDtls.ITEMNAME'; ...; ......; 
    })
}

Answer №1

If you're unsure about your goal, I recommend investing time in learning the async-await syntax. This allows you to write asynchronous code in a synchronous manner. In your specific case, it would look something like this:

(async()=>{
    const flavors = await getFlavours();//Waiting for a promise

    const itemIds=[]

    for(let flavor of flavors){
       const itemId =  await getItemIDs_ofeachFlavor(flavor.id);//Awaiting a promise for each flavor
       itemIds.push(itemId);    
    }

    for(let itemId of itemIds){
        const details  = await getItemDetails()

        //Perform actions with details..
    }


})()

Essentially, you await the resolution of each promise sequentially, retrieve its data, and then work with it.

To comprehend this process, ensure you have a solid understanding of Promises: Link to Promises Documentation

Following that, you can delve into async-await: Link to async-await Documentation

Additional info on Await Operator

Remember, this approach is most useful when dealing with asynchronous tasks like AJAX data fetching, as it appears you are doing here.

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

Identifying when two separate browser windows are both open on the same website

Is it possible to detect when a user has my website open in one tab, then opens it in another tab? If so, I want to show a warning on the newly opened tab. Currently, I am implementing a solution where I send a "keep alive" ajax call every second to the s ...

Having trouble with test coverage in Mocha using Blanket?

I have a Node application that I want to test and generate a coverage report for. I followed the steps outlined in the Getting Started Guide, but unfortunately, it doesn't seem to be working correctly. In my source code file named src/two.js: var tw ...

Error encountered in a Node.js Express application: 'Error in Jade template (version 1.0+): The usage of duplicate key "id" is not permitted.'

Seeking guidance on the following issue: Within my Express app, I am providing numerous parameters to a Jade template, resulting in an error message that states: Duplicate key "id" is not allowed. (After reviewing, I have confirmed that there is no para ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

The deletion function necessitates a switch from a server component to a client component

I built an app using Next.js v13.4. Within the app, there is a server component where I fetch all users from the database and display them in individual cards. My goal is to add a delete button to each card, but whenever I try to attach an event listener t ...

Issue with the scope of Bootstrap Accordion

Observing that the event triggers on a single Bootstrap accordion can affect all other accordions on the same page, I am wondering if there is a way to isolate this behavior without altering the markup or using $(this). Any suggestions? Check out this exam ...

The $rootScope object cannot be accessed in the controller

At module run, I created a $rootScope that is accessible from the view. However, I am struggling to access this value inside another controller. Can someone please suggest a way to achieve this? I attempted to make the datepicker popup options available ...

Maven, Protractor, and Selenium WebDriver team up for efficient integration testing

Our team has developed a web application that utilizes Java on the back-end and Angular for the user interface, with Maven serving as the build system. We've been working on setting up automated integration testing with Protractor, but despite extens ...

Horizontal Panning Feature for D3 Horizontal Bar Charts

I am working on a D3 Bar Chart and I would like it to have horizontal panning functionality similar to this example: https://jsfiddle.net/Cayman/vpn8mz4g/1/. However, I am facing an overflow issue on the left side that I need to resolve. Below is the CSV ...

Tracking Time Spent in a Tab using HTML and JavaScript

I have a unique issue that requires a specific solution. Despite my extensive search across the internet, no useful answers were found. This is the snippet of HTML code in question: <form action="/timer.php" method="POST"> <span>Fir ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

Alert: Next.js 13 console error detected

Currently, I am utilizing Next js 13 for the development of a website. However, I have encountered this warning in the console: The resource http://localhost:3000/_next/static/chunks/polyfills.js was preloaded using link preload but not used within a few s ...

Organizing the directory layout for the /profile/username/followers route in NextJs

I want to set up a folder structure for my website that can accommodate the URL /profile/username/followers, where the username will be different for each user. The proposed folder structure is as follows: pages -- profile -- [username].js Curren ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

Real-time list refreshing using ng-repeat

I am encountering an issue with using ng-repeat in a table to create a folder tree structure. When I click on a specific row and update the value based on a certain condition by calling a function via "onclick" (since ng-click is not working), the JavaScri ...

Unable to view text in Angular 1.5 controller

Trying to grasp the concepts of angular 1.5 has been a challenge for me, specifically in regards to displaying text on the webpage using controllers. Instead of showing the desired content, it just displays event.name. The file in question is EventDetails ...

Angular select tag failing to display input data accurately

When constructing select type questions for my web app using a JSON file, the code snippet for the select tag appears as follows: <div class="form-group" ng-class="{ 'has-error': form.$submitted && form[field.id].$invalid }" ng-if="fi ...

What is the best way to divide an array while extracting data from a JSON object using

Currently, I am parsing the json data. My goal is to find a specific property within the json object that contains two nested arrays (list and array). However, when extracting the values, they are all being stored in a single array. Is there a way to separ ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

IE does not support hover effects

Having trouble with a hover effect that works in Chrome but not in MSIE. Are there any alternatives or fixes to make it work in MSIE? The hover/rollover effects I've tried all seem to have this issue in IE. normalize.css demo.css set2.css font- ...