I'm new to Javascript and am having trouble understanding async functions (particularly the query function). I have a working query below but need to return the results of that query as an array.
const allComedians = "Comedians";
let shows = ["Heat 1","Heat 2","Heat 3","Heat 4","Heat 5","Showcase 1","Showcase 2","Showcase 3"];
let showKeys = ["1","2","3","4","5","6","7","8"];
let ActiveComedians = [];
function initialize () {
for (let x = 0; x < shows.length; x++){
if (project.title === shows[x]){
wixData.query(allComedians).contains("showKey", showKeys[x])
.eq("isActive", true)
.find()
.then((results) => {
for (let i = 0; i < results.items.length; i++){
let add = results.items[i].title.trim();
ActiveComedians.push(add);
}
})
.catch((err) => {
console.log(err);
})
return ActiveComedians;
}
}
}
Thanks in advance for any clarity you are able to provide.
The above code runs the desired query and delivers the expected results, but I am unable to access the contents of my array ActiveComedians because it isn't returned until after all other parts of my script execute.
In JavaScript, asynchronous functions do not return immediately.
The query continues running in the background while your function continues executing, resulting in ActiveComedians being returned before it's populated.
To fix this, you need to wait for the query to finish using .then()
. Here's the simplified version of your code:
const allComedians = "Comedians";
let shows = [
"Heat 1",
"Heat 2",
"Heat 3",
"Heat 4",
"Heat 5",
"Showcase 1",
"Showcase 2",
"Showcase 3",
];
let showKeys = ["1", "2", "3", "4", "5", "6", "7", "8"];
let ActiveComedians = [];
function initialize() {
for (let x = 0; x < shows.length; x++) {
if (project.title === shows[x]) {
return wixData
.query(allComedians)
.contains("showKey", showKeys[x])
.eq("isActive", true)
.find()
.then((results) => {
for (let i = 0; i < results.items.length; i++) {
let add = results.items[i].title.trim();
ActiveComedians.push(add);
}
return ActiveComedians; // Return after query finishes
})
.catch((err) => {
console.log(err);
});
}
}
}