I am trying to migrate my API from XMLHttpRequest to JavaScript fetch for API call. But I am unable to obtain the desired result.
My main script calling the API:
response = API.get_data()
My API code:
var API = new function() {
this.get_data = function ()
{fetch(url)
.then(function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' + response.status);
return;
}
response.json().then(function(data) {
return data;
});
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
}
The network call takes place and the response data is retrieved but I am unable to obtain the response in main script. How do I do it?
Do I need to use a callback function to the main script passing the response data? Or is there any pre-defined method that I have missed?