0

I am creating a pure JavaScript module and I'm trying to call some data from an API, this completes successfully and if I assign the response to a variable and then log it to the console then I see the expected results. However if I return it then I receive undefined. Apologies if this has been answered already but I was unable to find the answer to my question after browsing for some time.

My code is as follows:

                httpRequest.onload = function() {
                    if(httpRequest.readyState === 4) {
                        if (httpRequest.status === 200) {
                            response = JSON.parse(httpRequest.responseText);
                            console.log(response) // Returns data correctly
                            return response;
                        } else {
                        console.log("API call error");
                        }
                    }
                }

The above code returns to another function outside the module as follows:

console.log(module.callAPI(query)); //returns undefined

Any insignt would be appreciated.

Thanks!

Vistari
  • 697
  • 9
  • 21

1 Answers1

1

You return the value from onload() method but you're trying to log result of callAPI() method.

The onload() is a callback which will be called "sometimes in the future" - once the request completes. Returning anything from it doesn't make much sense. If you share what you're trying to achieve we can give you some tips. Logging to console from the onload() as shown in your question is 100% appropriate.

Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
  • Thanks for the response, I'm fairly new to JavaScript so how would you advise I return the response object? – Vistari Nov 16 '14 at 15:46
  • Usually you take actions from the `onload()` itself rather than returning the value. As the callback is asynchronous "returning a value" is usually not what you want. Calling some method like `updateUIWithTheReceivedResponse(response)` would be appropriate for example. – Jan Zyka Nov 16 '14 at 15:48
  • Ah I see, thanks! I had managed to get it to work that way by creating a method to output the array in the HTML but I wanted the module to be completely independent of the web page so that it would just return an array of elements that you could manipulate how you saw fit from outside the module. Is this possible/ should it be done? – Vistari Nov 16 '14 at 16:05