Problem with Async functions

Hello!
I started getting in to the concept of async sometime ago, but I am having some problems…


So this code basically does some queries to find out which dates are not available for bookings, using a for loop (line 31) for 30 days(30 loops).
For each loop:
Once it reaches to line 67, it now knows if a date is available by checking the totalcount of the query.
If it is 0 (Line 69) it gets the previous blocked dates of the datepicker, and adds the new blocked date to that (lines 71,72,73)
I tried several ways of using async but I’m not sure I have found the correct one…

The problem
Once it reaches to line 72 I had a console.log to print the var dt (which is the current loop date )
I get 2 logs, 3th of September , and 4th of September .
That is wrong .The dates with no availability is 1th and 2nd . So I am guessing the date goes to the next loop and it logs the new loop date…or something like that…
I’ve been trying to solve this for hours now and I just can’t figure out what is going on…
Can someone help?

I tried giving an 60ms delay within the loops (line 32,33,34) and **line 78 ** but doesn’t seem to fix the problem.

Hello Maria,

Your code looks good except for the uses of async and await mixed in with .then() function, usually one is used and not both as it can cause some tricky errors.

To fix it replace your .then() with await like so -

line 40 changes:

let results = await wixData.query('BookingCreated')
                .eq('chefId', chef)
                .eq('date', dz)
                .find()
                
//...rest of your code

line 59 changes:

let res = await wixData.query('BookingAvailability') 
                .eq('chefId', chef) 
                .eq('date', dz) 
                .not(
                      wixData.query('BookingAvailability')
                      .between('time', start, end)
                )
                .find() 
                
//...rest of your code

Also I recommend removing the setTimout() function as setting an arbitrary timeout on your site is usually never a good idea, and just hinders performance.

Best,
Majd

That was it :slight_smile:
Can’t thank you enough!!!
Thank you!!

So–just is it good as a general rule when i’m working with this type of proccess to do it like the way you indicated above?

async function thefunction(){
let results = await wixData.query('Database') 
//This line will run after the first query
let results2 = await wixData.query('Database2') 
//This line will run after the second query
let results3 = await wixData.query('Database3') 
//This line will run after the third query
}

Hello Maria,

Using async/await is one of the more popular methods these days to deal with async code, however there are other methods like the .then() you were using. I recommend using async/await but learning how it got to this point from callbacks, to .then(), to using async.

Best,
Majd