I’ve had this sequencing problem a few times and never really figured it out. In this case I was trying to use a loop to fill an array with details of Pricing Plans, but really it could be any loop that calls a function requiring a bit of extra time to complete.
[I’ve simplified the code here just as an example. There is one backend GetPlan() call, but the API that is called is irrelevant to the example.]
import { getPlanInfo } from "backend/GetProfilePlanInfo.jsw";
const plan = [] // global array for plan IDs
plan[0] = "96b377b4-9608-4f83-a716-30cf03b4a1bf"
plan[1] = "cb0b9563-661b-45d1-b4c5-8c5eab7be7f6"
plan[2] = "2932dfed-23fc-408a-bdbe-c3ccc5c1cb6d"
$w.onReady(async function () {
for (let i = 0; i < 3; i++){
await GetProfilePlan(plan[i], i);
console.log("C. Plan ID " + i);
}
});
function GetProfilePlan (planID, index){
console.log ("A. Item " + index)
getPlanInfo(planID, {suppressAuth: true})
.then((result) => {
console.log ("B. " + plan[index])
})
}
Based on the code, I would expect each “for i… i++” iteration to run through items A B C once on each pass, so the console should read A B C 0, then A B C 1 then ABC 2. My thinking was that even if GetProfilePlan() takes time the “await” statement should not allow the loop to progress until the function has completed.
Instead, when I run the code I get A C 0, A C 1, A C 2, [then after a lag] B0, B1, B2. And I get the same result with or without “await” command.
Here is my console result:
Any ideas what’s wrong and how to ensure GetProfilePlan() is completed for each iteration in sequence?