The below code works to send a GET API request. It returns data for a company name in a JSON HAL format within the function 'httpGet(name)'. The console.log(http.response) command does log the expected result. However, the subsequent return http.response returns 'undefined' when called in another function.
Could someone explain what I'm (obviously) doing wrong. Much appreciated!
function httpGet(name) {
const http = new XMLHttpRequest();
const url = "https://api.overheid.io/suggest/openkvk/" + name + "?ovio-api-key=MYKEY" // MYKEY is equal to my API key
http.open("GET", url);
http.send();
//http.onload = () => console.log(http.response);
http.onload = function() {
let text = http.response
var id = text.split('id":"')[1]
id = id.split('",')[0]
const url = "https://api.overheid.io/openkvk/" + id + "?ovio-api-key=MYKEY" // MYKEY is equal to my API key
http.open("GET", url);
http.send();
http.onload = () => console.log(http.response); //returns the correct http.response as a JSON HAL repsonse
return http.response; // returns undefined when the function is called. Example (other function): console.log(httpGet('Heineken')) returns 'undefined'
}
}