Skip to content
Advertisement

Method returns undefined the first time it is called

I have a method that selects distinct values from a database as shown below:

JavaScript

I then have a button with the method POST and action /categories

The displayCategories is called when the button is clicked as follows:

JavaScript

I added some console logs for test purposes. The issue I am having is that the first time I click the button, it returns undefined. Each time I click it again, it prints the correct data for session.categories as shown below:

categories

Is there a simple fix for this issue?

Advertisement

Answer

The code is calling a displayCategories as if it were synchronous, but it is running asynchronous code with the callback.

There are multiple possible solutions for that but one of them would be to use Promises, like the following:

JavaScript

And the other part with an async function

JavaScript

But that’s just to make your issue go away, if you want to improve the code even further you can just keep the responsibility of dealing with request and response with the controller action and just use the other function to get the data you want, isolation its responsibility:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement