WixData.query question

I have built my function in a .jsw file. I don’t want it on my page code, as I plan to use this as a common function.

I want to call my function from my page, but for some reason, the function cannot return with the dataset. Is there any way to do this?

Example .jsw function:

export async function getResults ( myID )
{
let myQuery = wixData . query ( “clients” );

**if** ( myID  !=  **null** ) { 
    myQuery  =  myQuery . eq ( "clientid" ,  myID ); 
 } 

myQuery . find () 
    . then ( ( results ) => { 
        **if** ( results . items . length  >  0 )  
        { 
            myResults  =   results . items 
        }  
        **else**  
        { 
            myResults  =   results . items 
        } 
        
    } ) 
    . **catch** ( ( err ) => { 
        **let**  errorMsg  =  err ; 
    }  
    ); 
    **return**  myResults 

}

Is there any way to get this function to return the array of results?

Thanks!

What if MyID is not Null, but undefined? I would test like:

if (myID){
	myQuery=myQuery.eq("clientid",myID);
}
else{
//here do something in case MyID is empty, null, undefined, etc
}

And something else. What are you trying to achieve with this:

if(results.items.length>0){
	myResults=results.items
}
else{
	myResults=results.items
}

I am trying to return the results array, which I will use to populate my datatable. It there are no results, that is OK, zero rows will populate. I already do it using SQL code, but was thinking to use wixData instead.

My equivalent SQL code is this:
.
.
.
const results = await sql ( mySQL );
return results . payload . data . rows ;

}  
**catch**  ( error ) { 
    console . error ( error ); 
}

But in your sql-example you await the result. But you don’t do that in your wix-data code. You declare it async, but then you do not wait for the promise to resolve, you return myResults, which is not resolved yet.
So you either use async/ await or move the return upwards using .then (and remove async from function declaration). Have a look at some backend examples in API docs how and where to put the return.

I believe that you are making the mistake of not distinguishing between backend and frontend code. The wix-data examples are usually all frontend (if you see $w in an example, it is always frontend).