Reputation: 25
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?
Upvotes: 0
Views: 716
Reputation: 2497
The response can be accessed in the promise, so what used to be your callback should go in the then body.
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(data => {
// do something with data here. you cannot return data because this is asynchronous
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
}
Upvotes: 0
Reputation: 77039
First, you need to return
the result of fetch()
from your API method. Notice that, in get_data
, you call fetch()
but don't return
the result.
return fetch(url).then(...)
Second, in your main script, you need to treat the result as a Promise
. fetch()
gives get_data()
a Promise
of a Response
, and get_data()
gives the main script a Promise
of data
.
API.get_data().then(function(data) {
// Same thing you did for fetch, you must do with get_data
})
If you don't understand why this must be the way, take a look at the magnificent answer to this question: How do I return the response from an asynchronous call?
Upvotes: 1