Problem with calling functions from web modules

Hi,

I am facing problems with calling functions from the web modules.

I am trying to do up a member profile page whereby the create button is enabled (and the update button is disabled) when there is no corresponding record in a ‘Members Table’.

If there is a corresponding record, the create button is disabled (and the update button is enabled).

Backend code (File Name - trialBacData.jsw):

import wixData from ‘wix-data’;

export function getUsDa(userRetrievalID) {

wixData.query("Members").eq("userID",userRetrievalID).find().then(results => { 
	 
	 let finalResult; 
	 
	 if(results.length===1) 
		
		{ 
			finalResult = true; 
			
		} 
		
	else 
	
	{ 
		finalResult = false;   
		
	} 
	 
	 console.log(finalResult); 
	 
**return finalResult;** 

} );

}

Front End Code:

import wixUsers from ‘wix-users’;
import wixData from ‘wix-data’;
import wixLocation from ‘wix-location’;
import {getUsDa} from ‘backend/trialBacData’;

$w.onReady(function () {

var usID =  **wixUsers.currentUser.id** ; 

console.log("Hello World"); 


getUsDa(usID).then(result => { 
	
	console.log(result); 
	
		if(result) 
		
		{ 
			$w("#createBtn").disable(); 
					
			$w("#updateButton").enable(); 
			
		} 
		
	
	

	}); 

Result:

When I logged the result into the console, all i get is a null value when ideally i should have gotten a true or false value .

Can anyone help me out with this code? Maybe point out the mistakes please ><

Try returning the query itself. This should return the final result. It has to do with how promises work.

//...

return wixData.query("Members").eq("userID",userRetrievalID).find().then(results => {

//...

Thanks. I resolved the issue after following your advice and experimenting with some code variations.

Sorry, what exactly is a Promise?

How does it affect its use in Wix Code?

Let me know if this helps you understand promises: https://www.wix.com/code/home/forum/questions-answers/code-check-function-return-promise.

The trick, I have discovered is as follows:

Instead of returning the finalResult as:

return finalResult;

you need to return a Promise. Since it is a result and therefore resolved the thing to do is resolve the Promise immediately. So the result needs to look like:

return Promise.resolve(finalResult);

Now in front-end code you can call the backend function with then:

getUsDa(usID).then((finalResult) => {
console.log(finalResult);
if(finalResult)
{
$w(" #createBtn “).disable();
$w(” #updateButton ").enable();
}
});