I am having this sample of code and would like to understand why the if condition is executed before wixdata.query is termined
console.log("zzzzzz xchalet, xdtbegin to xdtend = " + xchalet + " , " + xDtBegin + " , " + xDtEnd); wixData.query("booking") .eq('"' + xchalet + '"', true) .between("bookDate", xDtBegin, xDtEnd) .find() .then((res) => { ...
if (resCount === 0) { isConflit = false; ...
let bookupd = wixData.query("booking") .between("bookDate", xDtBegin, xDtEnd) .find() .then((res2) => { ...
isConflit = false; ...
console.log("isConflit is " + isConflit); console.log("isConflit is " + isConflit); console.log("isConflit is " + isConflit); console.log("isConflit is " + isConflit); if (isConflit) { $w('#stateboxBook').changeState("noBook"); return console.error("Erreur1 conflit d'horaire"); } else { $w('#stateboxBook').changeState("bookOK"); }
My log below prove that the code highlight in yellow is executed prior than the green's one is finished.
isConflit is true
isConflit is true
isConflit is true
isConflit is true
Erreur1 conflit d'horaire
###########Data Booking is for chalet 0 b22 ######date from to 20211219 20211220
catch first call 777777 false
Data Booking to update for chalet resCount22222222= 1 ######
222222222 =false
rec booking Before=
rec booking Before=
rec booking AFTER=
rec booking AFTER=
How can I wait the end of the execution of the green part prior excuting the yellow one?
Also, JS code is never run " in order ". Please check this to learn more: https://blog.bitsrc.io/understanding-asynchronous-javascript-the-event-loop-74cd408419ff
That why, you need to use .then() OR await to make the code wait for the data ready and continue using the data taken.
@Youge Anytime that you make a call to wixData, it takes some time for the query to successfully return the resulting data. Meanwhile, the code continues to execute below the queries. You will need to put any code that depends on the query results, in the .then area after the second query's returned promise.
For a thorough explanation, you can read this helpful article .