Return function value from query result

Hi, I wrote this code and it works great except I cannot get the return value outside of the query function. please help!

function getRefItems(dataSetName,itemId,refFieldKey){
var titlesArray = [];

wixData.queryReferenced(dataSetName, itemId , refFieldKey).then( (results) => { 
          **let**  items = results.items; //see item below 
          **for**  ( **var**  i = 0; i < items.length; i++) { 
               titlesArray[i] = items[i].title; 
          } 
          console.log(titlesArray);      // here it works. 
}); 

return titlesArray; // doesnt return the array outside the wixData.query()
}

Hello

The problem here is that the titlesArray is being returned before the promise is resolved.
Try using async and await


async function getRefItems(dataSetName,itemId,refFieldKey){
    var titlesArray = [];

   let results = await  wixData.queryReferenced(dataSetName,itemId,refFieldKey)
   let items = results.items; //see item below
   for (var i = 0; i < items.length; i++) {
        titlesArray[i] = items[i].title; 
} 
console.log(titlesArray);      // here it works.
    
return titlesArray;       //should work now
}

Best
Massa

Hello,
I have the same issue here, I try to add async/await declarations like you said but I still have some issues. Here my code:

async function QueryAndCalcul (nomChamp,valueUser) {
let CO2ValueUser
let results = await wixData.query(“alimentation”)
.eq(“aliment”, nomChamp)
.find().then(() => {
CO2ValueUser = valueUser * results.items[0].portion * results.items[0].qte_co2Portion
console.log(CO2ValueUser); // cannot see this console log on the console panel
})
return CO2ValueUser; // does not seem to return anything
}

Thank you for your help