Code after while loop not running

Hi, I have an async function with a while loop in it that’s working perfectly fine, except for the fact that the code that should run after the while loop is completed isn’t running at all.

async function nextItem() {
var i = 0;
var totalCount = $w(“#dataset3”).getTotalCount()
while (i < totalCount) {
console.log($w(“#dataset3”).getCurrentItem())
$w(“#dataset3”).setFieldValues({
“suburb”: $w(“#suburbInput”).value,
“region”: $w(“#regionDropdown”).value
});
const item = await $w(“#dataset3”).next()
i = i + 1;
}
console.log(“Next item function completed.”)
[wixLocation.to(“/add-listing”)](wixLocation.to(“/l41-1w2htp-1hn1f1e”)
})
}

So neither the console log nor the wixLocation.to is running when the while condition becomes false and I’m not sure why this is the case. Any ideas?

Have a read about using asynchronous code here.
https://support.wix.com/en/article/corvid-working-with-promises
https://www.wix.com/corvid/forum/corvid-tips-and-updates/promises-promises

thanks for replying @givemeawhisky . I still don’t understand why the code after the while loop isn’t running at all. I’ve tried putting it after I call the nextItem function in a then() but I don’t think I’m doing this right →

nextItem()
.then(()=>{
console.log(“Next item done”)
wixLocation.to(“/add-listing”)
})

Can you please suggest to me where I need to put the wixLocation.to so that it runs after the nextItem() function is completed?

Try this:

async function nextItem() {
let i = 0;
const totalCount = $w(“#dataset3”).getTotalCount();
await Promise.all([
( async () => { await while (i < totalCount) {
console.log($w(“#dataset3”).getCurrentItem())
$w(“#dataset3”).setFieldValues({
“suburb”: $w(“#suburbInput”).value,
“region”: $w(“#regionDropdown”).value
});
const item = await $w(“#dataset3”).next();
i++;
}
console.log(“Next item function completed.”);
})(),
( async () => { await wixLocation.to(“/add-listing”) })()
]);
}

Also note that the constant in red doesn’t seem to be doing anything useful, you can just change it to
async function nextItem() {
let i = 0;
const totalCount = $w(“#dataset3”).getTotalCount();
await Promise.all([
( async () => { await while (i < totalCount) {
console.log($w(“#dataset3”).getCurrentItem())
$w(“#dataset3”).setFieldValues({
“suburb”: $w(“#suburbInput”).value,
“region”: $w(“#regionDropdown”).value
}). then ( () => { i++; $w(“#dataset3”).next(); })
} })(),
( async () => { await wixLocation.to(“/add-listing”) })()
]);
}