user5415371
user5415371

Reputation:

Understanding Fetch() Javascript

I am going through a javascript tutorial, and I need some help in understanding the pattern in the following function:

get:  function(url) {
         return fetch(rootUrl + url, {
            headers: {
                'Authorization': 'Client-ID ' + apiKey
            }
        } )
        .then(
            function(response) {
                return response.json();
            }
        );
    }

What I am confused about is, what is the point of returning fetch() if we only actually care about response.json()?

Upvotes: 1

Views: 332

Answers (2)

Barmar
Barmar

Reputation: 782106

It's not returning fetch(). When you write chained function calls like:

return f1(args).f2(otherargs);

it's equivalent to:

var temp1 = f1(args);
var temp2 = temp1.f2(otherargs);
return temp2;

So your function could be written as:

get: function(url) {
    var promise1 = fetch(rootUrl + url, {
        headers: {
            'Authorization': 'Client-ID ' + apiKey
        }
    });
    var promise2 = promise1.then(function(response) {
        return response.json();
    });
    return promise2;
}

Now you can see that it returns the promise that, when it's fullfilled, returns the JSON from the response.

Upvotes: 1

guest271314
guest271314

Reputation: 1

return fetch for ability to chain .then(), .catch() to .get() call, e.g.,

obj.get(url).then(function(data) {
  console.log(data)
})

without return statement obj.get(url).then(handler) could log error if object does not have property named then where value is a function which handles Promise returned from fetch, where no value is returned from get function

var objWithReturn = {
  get: function(url) {
    return Promise.resolve(url)
      .then(
        function(response) {
          return JSON.parse(response);
        }
      );
  }
}

objWithReturn.get('{"a":1}')
  .then(function(data) {
    console.log(data)
  })

var objWithoutReturn = {
  get: function(url) {
    Promise.resolve(url)
      .then(
        function(response) {
          return JSON.parse(response);
        }
      );
  }
}

objWithoutReturn.get('{"a":1}')
  .then(function(data) {
    console.log(data)
  })

Upvotes: 2

Related Questions