[英]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.