0

Now I am using JavaScript function coded as follows:

self.fillSelect = function (key) { 
             html = "<option value =''>choose</option>";
            self.getGroupOptions(key, function (res) {
                for (let a = 0; a < res.length; a++) {
                    html += "<option value = '" + res[a].Code_Name + "'>" + res[a].Code_Name + "</option>";
                   
                }
            }, function (err) {
            });
            return html;
        }

As I know or understand the html variable is a global variable and can be accessed in any place in the function. In this function this logic happens after the return statement. This function just returns

<option value =''>choose</option>

then enters the loop with no result...why is that happening??

self.getGroupOptions()

This function is a jQuery AJAX request to get options from database

Khairy
  • 56
  • 6
  • 2
    The ajax request is asynchronous and you're not waiting for it to complete, so you're returning html before the `getGroupOptions` callback function runs. – ray Jan 02 '22 at 02:06

1 Answers1

1

TLDR

You should learn about javascript asynchronous functions and callbacks. The for loop that populates the html is inside a function that gets called later, in async.

Long version

JavaScript is single threaded, that means that there is a single line of execution and things cannot happen "at the same time" in two places of a JS software, be it a page or a node JS application.

To work around this "feature", in JS is very common to run async operations providing a callback.

The underlying system (in this case, the browser) will perform the operation (in this case, an AJAX call) and then "call back" your code by invoking a provided function.

This is what is happening in this case, the call to AJAX happens later, your code return before.

Then when the AJAX call happens, you call is called as part of the "call back", the for loop executes, the html variable is filled, but at that moment is too late to return it.

You should return a Promise and register a callback on that promise to be able to retrieve the html content later, when all the AJAX stuff and callback is completed.

Simone Gianni
  • 11,426
  • 40
  • 49