[英]How to use while loop inside an async function - newbie question
为什么这个 function 不循环遍历返回到我调用它的位置的数组? 我很确定这与我在异步 function 中的使用有关,但我无法弄清楚。
我尝试在while循环之后使用return,但是由于异步而立即触发,我也不知道如何成功地将它放入循环中。
所有帮助表示赞赏。
这是代码的简化:
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++;
}
}
}
这是完整的代码:
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++;
}
}
}
我不确定您的其他功能是否能解决这些承诺。 但是您可以尝试以下类似的方法。 我将添加虚拟承诺。
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
代替
while (i <= n)
和
while (i < n)
我试图循环一个太多次。
经过反思,我应该将等待包装在 try...catch... 中,并且我会更快地发现错误。
感谢您的所有贡献
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.