Category: How do I do X?
Resource links
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How Do I Get the Return Value of the API in JS Object, Because the API Is Asynchronous

Issue

I am having trouble getting the correct return value from an asynchronous API in my JS function. Whenever I try to immediately access the data, it returns the wrong value. I need a solution to retrieve the correct data value.

Resolution

To obtain the return value from an asynchronous API call and use it in a JavaScript object, you should handle the asynchronous nature of the API call with promises or async-await functions. These functions manage the waiting process internally, allowing the execution to pause until the API response is received and processed.

Here’s how you can implement this:

export default {
    	async getData() {
		try {
			//Call the REST API you created in Appsmith
			const data = await getUsers.run();
			console.log(data);
			//prints the response generated by the query
			console.log(getUsers.responseMeta);
		} catch (error) {
			console.error(error);
		}
	}
}

In this code snippet, the getData function uses async-await to fetch the data from the API (getUsers) and reads the response generated by the API from the responseMeta object. For more information on Appsmith queries and their responses, see query object.