Phương Nguyễn
Phương Nguyễn

Reputation: 8905

What kind of code being written on AngularJS?

I was reading through angularjs source code of $http and I was like: WTF?

Look at this line: https://github.com/angular/angular.js/blob/master/src/ng/http.js#L739

  promise.success = function(fn) {
    promise.then(function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

  promise.error = function(fn) {
    promise.then(null, function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

  return promise;

  function transformResponse(response) {
    // make a copy since the response must be cacheable
    var resp = extend({}, response, {
      data: transformData(response.data, response.headers, config.transformResponse)
    });
    return (isSuccess(response.status))
      ? resp
      : $q.reject(resp);
  }

What's the point of defining transformResponse function after the return promise? It would never get executed, right? Also inside that file, I find other place where angularjs team keep adding code after a return statement.

Is there some magic being thrown here or I'm just on high?

Upvotes: 1

Views: 71

Answers (1)

Long story short, if you don't have the time to read calebboyd's link, you can do that because

    function transformResponse(response) {...}

is a function declaration that gets hoisted.

It will work for exactly the same reason that this will work aswell:

    mySuperSweetFunction(); // will return 'hi there'

    function mySuperSweetFunction() { return 'hi there!' }

However if you did this:

    mySuperSweetFunction(); // will throw exception.

    var mySuperSweetFunction = function() {return 'hi there'}

It wouldn't work, because although you're declaring a function, you are also making an assignment to a variable. In this case the order you write your call does matter.

Upvotes: 2

Related Questions