Search code examples
angularjsangularjs-serviceangularjs-http

Return value from nested http.put


How to return response object from http.put to controller as return value from TestFunction? response from http.get is printed OK but putResponse is undefined. During debug I can see that http.put updates data on server.

  testFunction: function (url, data) {
        var etag;
        var putResponse;
        $http.get(url).then(function successCallback(response) {
            if (response.data != null) {
                etag = response.headers(['etag']);
                 $http.put(url, data, { headers: { 'If-Match': etag } }).then(function successCallback(response) {
                     putResponse = response;
                }, function errorCallback(response) {
                    // handle error
                });
            }
            else {
                // handle error

            }

        }, function errorCallback(response) {
            // handle error

        });
        console.log(putResponse);

    }

Solution

  • $http.get and $http.put are executed asynchronously from the rest of the code. you have that console.log out of the async call. so it gets called before the return.

    Furthermore If you want the putResponse returned to the "caller" you have to return both putResponse and the promise:

      testFunction: function (url, data) {
            var etag;
            var putResponse;
            var promise = $http.get(url).then(function successCallback(response) {
                if (response.data != null) {
                    etag = response.headers(['etag']);
                    return $http.put(url, data, { headers: { 'If-Match': etag } })
                }
                else {
                    // handle error
                    // $q.reject();    
                }
    
            }).then(function successCallback(response) {
                putResponse = response;
                console.log(putResponse); // this gets called after the server responds ( defined ) 
                return putResponse;
            })
            ["catch"](function (response) {
                     // handle error
            });
    
            console.log(putResponse); // this gets called before the server responds ( undefined )
            return promise;
        }
    

    now you can use

    tesFunction(arg1, arg2).then(function(response){ /* in here you have response defined */ })