在for循环内部插入一个Promise的方法

huangapple go评论71阅读模式
英文:

How to insert a promise into a block of code inside a for loop

问题

只有if级联结构在for循环内部运行,因此在#text中返回了几种食物,但实际上没有array[0]、array[1]和array[2],for循环应该运行到if(Number.isNaN(index)) {array.pop()},而array.sort((a, b) => a - b)应该保持暂停,直到for循环遍历所有食物为止。

(注意:我不能将if级联结构放在for循环外部,因为排名考虑了更多信息,而这些信息在这种情况下在for循环内部,这将涉及与promises相关的内容。)

我正在尝试在一个函数内部的for循环中运行两组代码,其中第二部分只有在第一部分完成后才执行。
英文:

I have some code here, the idea is to create a ranking on an index based on the prices and amount of nutrients of some foods within a Wix database:

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()
           }

           array.sort((a, b) => a - b);
           array.reverse();

           if (array[0] === index) {
             $w('#text1').text = item.food;
             $w('#text2').text = `${index}`;
           }
           if (array[1] === index) {
             $w('#text3').text = item.food;
             $w('#text4').text = `${index}`;
           }
           if (array[2] === index) {
             $w('#text5').text = item.food;
             $w('#text6').text = `${index}`;
           }
     }
 })
}

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

only the if cascade is running inside the for so it returns several foods in the #text but none is actually the array[0], array[1] and array[2], the for should run until the if (Number.isNaN (index)) {array.pop()}, and array.sort((a, b) => a - b); should remain on hold until the for has gone through all the foods.

(Note: I cannot place the if cascade outside the for because the ranking takes into account more information, which in this case is inside the for, it will have to be something related to promises)

I'm trying to run two sets of code inside a for loop inside a function, with the second part executing only after the first one completes

答案1

得分: 1

You try to sort and output your results inside your for loop without waiting it complete. That creates some mess. Just calculate the results and then use them:

async function calculate(nutrientId) {

  let items = await wixData.query('Food').find();
  
  // first calculate ranks
  
  items.forEach(item => item.rank = item[nutrientId] * item.grams / item.price);
  // you don't need reverse() just swap a and b
  items = items
    .filter(item => !isNaN(item.rank))
    .sort((a, b) => b.rank - a.rank)
  ;
  
  // do your 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(() => calculate(nutrientId));

(Note: I've translated the code portion, as you requested. If you need further assistance or have any questions, feel free to ask.)

英文:

You try to sort and output your results inside your for loop without waiting it complete. That creates some mess. Just calculate the results and then use them:

async function calculate(nutrientId) {

  let items = await wixData.query(&#39;Food&#39;).find();
  
  // first calculate ranks
  
  items.forEach(item =&gt; item.rank = item[nutrientId] * item.grams / item.price);
  // you don&#39;t need reverse() just swap a and b
  items = items
    .filter(item =&gt; !isNaN(item.rank))
    .sort((a, b) =&gt; b.rank - a.rank)
  ;
  
  // do your output
  
  for(let i = 0, index = 1; i &lt; items.length; i++, index += 2){
       $w(&#39;#text&#39; + index).text = item.food;
       $w(&#39;#text&#39; + (index + 1)).text = `${i + 1}`;
  }

}

$w(&#39;#button&#39;).onClick(() =&gt; calculate(nutrientId));

huangapple
  • 本文由 发表于 2023年5月21日 07:14:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定