1

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()?

2 Answers 2

2

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)
  })

Sign up to request clarification or add additional context in comments.

1 Comment

There's a typo in second example. should be: objWithoutReturn
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.