Ways to incorporate a promise within a for loop code block

In this code snippet, my goal is to create a ranking based on the prices and nutrient content of various foods in a Wix database. The process involves calculating an index for each food item:

function calculate() {
var array = [];
wixData.query('Food').find().then(res => {
        for (let i = 0; i < res.length; i++) {
          const item = res.items[i];

          const nutrientOfAmount = item[nutrientId];
          let grams = Number(item.grams);
          let price = Number(item.price);

          var index = (nutrientOfAmount * grams) / price;

          array.push(index);
          if (Number.isNaN(index)) {
                array.pop()
           }

     }
 })
}

$w('#button').onClick(() => calculate());

The issue I am facing is that the if cascade within the for loop is returning multiple foods in the #text but not properly assigning the correct rankings to array[0], array[1], and array[2]. This is because the sorting logic is executing prematurely. I need the sorting to occur only after the for loop has completed processing all the food items.

(Note: Due to additional information required for ranking inside the for loop, I cannot move the if cascade outside. It seems like it may involve utilizing promises for sequential execution.)

I am attempting to execute two sets of code sequentially within a for loop function, ensuring the second part runs only after the first one finishes.

Answer №1

By attempting to organize and present your findings within the loop, chaos ensues as the process is interrupted. It's better to first calculate the results and then proceed with their usage:

async function processResults(nutrientId) {

  let items = await wixData.query('Food').find();
  
  // start by determining ranks
  
  items.forEach(item => item.rank = item[nutrientId] * item.grams / item.price);
  // instead of using reverse(), swap a and b directly
  items = items
    .filter(item => !isNaN(item.rank))
    .sort((a, b) => b.rank - a.rank)
  ;
  
  // display the output
  
  for(let i = 0, index = 1; i < items.length; i++, index += 2){
       $w('#text' + index).text = item.food;
       $w('#text' + (index + 1)).text = `${i + 1}`;
  }

}

$w('#button').onClick(() => processResults(nutrientId));

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

What is the best way to retrieve the coordinates of highlighted text within input or textarea fields?

I am currently developing a Chrome application that involves injecting JavaScript code into a webpage. Whenever a user selects text, a popup appears next to the selected text. To achieve this, I have implemented the following code to retrieve the coordinat ...

Show options via checkboxes

Looking to create a dynamic leaderboard for gym exercises, where users can select exercises from a database and have them appear as options in the navbar. Currently manually adding exercises, but seeking a more efficient solution using Bootstrap 5. Any tip ...

"Sticky Top Button That Stays in Place When Scrolling | Innovative CSS & jQuery

I've been inspired by the "Proceed to checkout" button on amazon.com and I want to recreate it. However, I'm facing a challenge as their website is not responsive and I can't find a way to view a device user agent in Chrome. To see what I&ap ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Embedding image URLs fetched from JSON data within <li> elements

I have successfully retrieved a JSON response, which is displayed using the code below: Within my HTML document, I have the following structure: <ol id="selectable"></ol> In my JavaScript code, I make use of the following: <script type=" ...

Unable to display content on the ejs file

Currently, I have been diving into the world of node.js and exploring how to manipulate data by writing and reading from JSON files. It has been an interesting journey so far; however, I encountered a hiccup. Specifically, when attempting to post new data ...

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...

Is it possible to attach a mouse click event to styled text?

Is there a way to specify a mouse click event for an element with a decoration applied to the text, matched with regex? The option to specify a hoverMessage is available, but I would like to find a way to execute a function based on which decorated text ...

Limiting the x-axis drag function in a grouped bar chart using D3.js

For those interested, here is the link to view the code snippet: http://jsfiddle.net/4tqn7162/1/. When dragging the bars left or right causing the width of svg plot to disappear, I am looking for a solution that can restrict this behavior without impacting ...

Managing promise errors by verifying the response

I am currently facing an issue where I need to handle inappropriate responses in the 'then' block of the code snippet below. getData().then(response => transformData(response)); I believe I need to implement something like this, but I am uns ...

Ways to retrieve the response object from an express application

I am currently working on developing a nodejs application with mysql and my objective is to have my controllers and messages separated into different files. Below are examples of what I am aiming for: First, here is a snippet from my auth controller file: ...

Reposition HTML elements using JavaScript

Is there a way to use JavaScript or jQuery to replace the image with class "fnone" located under the span element with class "ddlabel"? <span id="flat_title" class="ddTitleText "> <img class="fnone" src="images/pinc.png"> <span ...

Several SVG Components failing to function properly or displaying differently than anticipated

I've encountered a puzzling issue that I just can't seem to solve. Here's the scenario: I'm working on a NextJS App and have 5 different SVGs. To utilize them, I created individual Icon components for each: import React from 'reac ...

Issue with data updating in Angular rxjs with share, map, and filter functions

After gathering search criteria from a form, I have developed a method that retrieves an observable of talents. fetchTalents(searchCriteria) { return this._allUsers$.pipe( tap((talents) => console.log(talents)), map((tale ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

What is the best approach to updating multiple rows instead of just the first row using the update button located on both sides using PHP and AJAX?

Starting fresh, so I might sound like a beginner with this question. How can I make use of the update button to update specific rows instead of just the top row? Every time I try to update, it only works for the top row. Here's the code snippet from ...

Numeric keypad causing issues with setting minimum and maximum lengths and displaying submit button

I designed a password pin page that resembles a POS NUMPAD for users to enter their password. I am struggling to make the condition specified in the JavaScript function properly. Rule: Hide the submit button if the minimum input is less than 4 characters ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Problem with input field borders in Firefox when displayed within table cells

Demo When clicking on any cell in the table within the JSFiddle using Firefox, you may notice that the bottom and right borders are hidden. Is there a clever solution to overcome this issue? I have experimented with a few approaches but none of them work ...

React: Dynamically update text input based on selected option

After selecting an option, I want to display a new text input. However, the old value entered remains on the screen even when I change the selection. How can I improve this functionality? Any suggestions would be appreciated. class loadComponent extends ...