Why isn't this function to loop through an array returning to where I called it? 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.
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.
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.
Thanks for all your contributions
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.