Help getting Referenced field title.

I’m trying to get titles of referenced field and populate dropdown list. but mainFunction is always getting undefined although it returns correctly from getRefItem function. Any help ?

export function mainFunction {

wixData.query( 'ChildTable' ) 
    .find() 
    .then(res => { 

let options = [{ “value” : ‘’ , ‘label’ : ‘Choose one’ }];
options.push(…res.items.map(results => {
let name = getRefItem(results.filedId); //getting undefined ---- ERROR ----
return { ‘value’ : results.filedId, ‘label’ : name };
}));

         $w( '#dropdownlist' ).options = options; //dropdownlist 

    }); 

}
function getRefItem(recordId) {

wixData.query( ‘MasterTable’ )
.eq( “_id” ,recordId)
.find()
.then(res => {
console.log( res.items[ 0 ].title);//getting Title, that is CORRECT.
return res.items[ 0 ].title;
//prints the value of the first result
});

}

You need to handle the Promise returned by getRefItem(). Something like this (not tested):

getRefItem(results.filedId)
    .then( (name) => {
        return { 'value':  results.filedId, 'label': name };
    } );

Or you can use await:

let  name = await getRefItem(results.filedId);

See Returning in a .then( ) for details.

Thanks Yisrael.

I changed my code as below and now would like to know how to add conditions to wix query based on the value. I do not need the condition at line number 5 if clinic is Zero. If there is no way to do so, I need to add esle condition that has same codes except contains filter. That would be too long.

Thanks again.

export function populateDoctorsByClinics(clinic) {
let options = [{ “value” : ‘’ , ‘label’ : ‘select one’ }];
if (clinic !== “0” ) {
wixData.query( ‘HealthSchedules’ )
.contains( “clinic” , clinic) // Line number 5
.find()
.then(res => {
if (res.length > 0 ) {
let items = res.items;
let doctors = ;
for ( var i = 0 ; i < res.length; i++) { //for each doctor for particular clinic
let doctorId = items[i].doctor;
if (!doctors.includes(doctorId)) {
doctors.push(doctorId);
wixData.query( ‘HealthProfessionals’ )
.eq( “_id” , doctorId)
.find()
.then(
res1 => {
options.push(…res1.items.map(results => {
return { ‘value’ : results._id, ‘label’ : results.title };
}));
$w( ‘#ddlDoctors’ ).options = options;
}); // end child then

                    }  //end if  ( !doctors.includes(doctorId)) 
                }  //end for loop 
            }  // end if res.length 

        });  // end then 
}