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

In search of a render function that can effectively apply styles to HTML strings using React JS

I have been struggling to convert the result field value, including HTML attributes string, into respective styles for one column in my antd table. Below is the string I am trying to convert: The exhaust air requirements for fume hoods will be based on m ...

Optimizing jqGrid: Enhancing saveRow function to properly synchronize with editRow function

Exploring how to customize jqGrid's add function for my own needs. I have a navButton with specific requirements: When the user clicks the button, a new row in edit mode should appear on the grid. Once the user enters data and presses enter, the dat ...

Transitioning from one CSS id to another during page loading

Wondering how to fade in one CSS id on page load and then smoothly transition to another after a few seconds? Here are the ids: #background { background: url("images/am_photography_bg.jpg") no-repeat center -25px fixed; background-size: 100%; ...

Switch up a JSON string using JavaScript

I received a JS string through an AJAX API call containing data like this: {"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17} My goal ...

The enigmatic jQuery AJAX glitch is craving additional arguments

My website uses jQuery's ajax function to handle user signups. Despite using similar code throughout the site, I encountered an error while trying to execute the code below: Error Message: uncaught exception: [Exception... "Not enough arguments" nsr ...

Can you utilize npm to print a byte array on a printer similar to how it's done in Java using DocFlavor.BYTE_ARRAY.AUTOSENSE?

We are transitioning from an outdated Java application to a new Electron app. Previously, we triggered the cash drawer of a register by printing a byte array using DocFlavor.BYTE_ARRAY.AUTOSENSE. Can this same functionality be achieved with an npm package ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Utilizing ng-class with Boolean values in AngularJS

On my page, I have a pair of buttons that control the visibility of elements using ng-hide and ng-show. <a ng-click="showimage=true" ng-class="{ 'activated': showimage}" class="button">Images</a> <a ng-click="showimage=false" ng-c ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

Generating a dynamic clickable div using Angular 6

How can I create a user-friendly interface that displays an image with clickable divs around detected faces, allowing users to view specific attributes for each face? I'm looking for a solution where I can have divs or buttons around each face that t ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...

After clicking, the React mobile navigation fails to collapse

At a certain breakpoint, my mobile navigation bar appears with a MENU button. When the MENU button is clicked, the menu opens and the button changes to CLOSE. Clicking on CLOSE collapses the menu, returning the button to MENU. However, when I click on th ...

Steps for adding a JSON object to an unordered list

After receiving data from a web server, I created a JSON object using the code obj = JSON.parse(data). This object contains information about dinosaurs such as their name, group, diet, and period. This is what the JSON object looks like: [{"name":"Stauri ...

Upon removing an element, the button click event fails to trigger

I recently created a div that looks like this <div id="hidden"> <img src="photos/Close-2-icon.png" width="16" height="16"> <input id="add" value="Add field" type="button" > <input type='button' id=&a ...

Having trouble loading a chart with amcharts after sending an ajax request

I have integrated amcharts to create a pie chart. When I click a button, an AJAX request is triggered to fetch data from MySQL in JSON format. After receiving the JSON array, I pass the data to amcharts but the chart doesn't display. Oddly, if I redi ...

The challenges of $location.search().name and base href in application URLs

I am working on an Angular app and my URL appears as http://localhost:8080/personal?name=xyz. To extract the 'xyz' value in JavaScript, I am using $location.search().name. Here is a snippet of my code: app.js app.config(function ($locationProv ...

What is the process for creating the token?

I've encountered an issue when generating a token while creating a user account. Despite my efforts, I keep getting an empty set. What could be causing this problem? Could there be an error in the syntax? Take a look at the controller file: import m ...