简体   繁体   English

如何在异步 function 中使用 while 循环 - 新手问题

[英]How to use while loop inside an async function - newbie question

Why isn't this function to loop through an array returning to where I called it?为什么这个 function 不循环遍历返回到我调用它的位置的数组? I'm pretty sure it's something to do with my use of while inside an async function, but I can't figure it out.我很确定这与我在异步 function 中的使用有关,但我无法弄清楚。

I tried to use return after the while loop, but that fires straight away because of the async, and I couldn't work out how to put it inside the loop successfully either.我尝试在while循环之后使用return,但是由于异步而立即触发,我也不知道如何成功地将它放入循环中。

All help appreciated.所有帮助表示赞赏。

This is a simplification of the code:这是代码的简化:

let cardsData

async function assignDatesToAllCards() {
  await doAThing()
  let n = cardsData.length
  let i = 0
  await loopToSetDates()
  console.log("data ready") // this doesn't execute

  async function loopToSetDates() {
    while (i <= n) {
        let sendDate = await calculateSendDate(aDate)
        cardsData[i].sendDate = sendDate
        i++;
    }
  }
}

And this is the full code:这是完整的代码:

let cardsData

async function assignDatesToAllCards() {
  console.log("assigning dates...");
  await setCardsDataArray() //refreshes cardsData
  let n = cardsData.length
  console.log("n:" + n)
  let i = 0
  await loopToSetDates()
  console.log("Cards about to Update"); // this doesn't execute
  wixData.bulkUpdate("UserCard", cardsData) //nor does this

  async function loopToSetDates() {
    while (i <= n) {
        console.log("i:" + i);
        let targetDeliveryDate = await calculateTargetDeliveryDate(firstDate, i * frequency)
        let sendDate = await calculateSendDate(targetDeliveryDate)
        cardsData[i].targetDeliveryDate = targetDeliveryDate
        cardsData[i].sendDate = sendDate
        console.log(cardsData[i]);
        i++;
    }
  }
}

I'm not sure if your other functions resolve the promises.我不确定您的其他功能是否能解决这些承诺。 But you can try something like the below one.但是您可以尝试以下类似的方法。 I will be adding dummy promises.我将添加虚拟承诺。

async function assignDatesToAllCards() {
  console.log("assigning dates...");
  let n = 2;
  console.log("n:" + n)
  let i = 0
  await loopToSetDates()
  console.log("Cards about to Update"); // this doesn't execute
  console.log("UserCard") //nor does this

  async function loopToSetDates() {
    while (i <= n) {
        console.log("i:" + i);
        let x = await prompt();
        console.log(x);
        i++;
    }
    return true;
  }
}

assignDatesToAllCards();```

This is working.
Hope this helps

replace代替

while (i <= n)

with

while (i < n)

I was trying to loop one too many times.我试图循环一个太多次。

On reflection I should have wrapped the awaits in a try...catch... and I would have found the error much more quickly.经过反思,我应该将等待包装在 try...catch... 中,并且我会更快地发现错误。

Thanks for all your contributions感谢您的所有贡献

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM