Help with promises

As an ex COBOL programmer I struggle with promises but I can get simple promises to work. Can you please help with the following: I have function that loops round a collection and update some of the items. As it stands, the function returns after the loop - console.log(“end of loop2”) but the saves return later. I want it only to return after all the updates have taken place.

  • console log -
    end of promise
    reset_lunch_diagnostics promise
    save Alan Mellor
    save York Ride

export function reset_lunch_diagnosticsC(rid, grpSize){ //during testing reset Eve of ride updates etc
return new Promise( function (resolve, reject){
var update = false
console.log(“entry into reset_lunch_diagnostics” )
return wixData.query(“Lunches”)
.eq(“rideId”, rid)
.ge(“status”,0)
.find()
.then( (Lresults) => {
var cntT = 0
Lresults.items.forEach((item3)=> {
if (item3.status > 1) {++cntT}
})
console.log(“start of loop2”, Lresults.items.length)
Lresults.items.forEach((item3)=> {
if (item3.choice === “*** not now coming ***”) {update = true ; item3.choice = “Soup of the day” }
if (item3.status > 4) {update = true ; item3.status = 4}
else if (item3.status === 3 && cntT > grpSize) {update = true ; item3.status = 1; --cntT}
else if (item3.status === 4 && cntT > grpSize) {update = true ; item3.status = 2; --cntT}
if (update) wixData.save(“Lunches”, item3).then((lItem) => {console.log(“save”, lItem.name)})
})
console.log(“end of loop2”)
console.log(“end of promise”)
resolve(“done”)
})

})
}

https://support.wix.com/en/article/corvid-working-with-promises

Thank you for the quick response. I have read the document a number of times and if I could apply it to my situation I would. Which section applies to my situation, The .then’s are sequential not nested.

Well I’m very disappointed. The only advice I go was RTFM.
I now have a solution or a work around which seems to work for me.
Rather than wixData.save, I push item3 on to an array. When all done I call a recursive function with the array.

resolve(update_lunch_items(items)

function update_lunch_items(items) {
return new Promise( function (resolve, reject) {
if (items.length === 0) { resolve(“rest items update”); return }
let item3 = items.shift()
wixData.save(“Lunches”, item3).then((lItem) => {
resolve(update_lunch_items(items))
. catch (() => { console.log(“b”, items.length) })
})
})
}

The problem is the Lresults.items.forEach((item3)
The forEach uses an anonymous function and they must be synchronous.
https://lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795/