devdropper87
devdropper87

Reputation: 4187

promises in angular - POST request

I'm new to programming and was wondering why do you not need a promise on a post request, but you do on a get request?

var getAll = function() {
        return $http({
            method: 'GET',
            url: '/api/links'
        }).then(function(resp) {
            return resp.data;
        })
    }

    var addLink = function(link) {
        return $http({
                method: 'POST',
                url: '/api/links',
                data: link
            })
            //you don't need a promise on a POST!
    }

Upvotes: 2

Views: 113

Answers (2)

Ilya Kogan
Ilya Kogan

Reputation: 46

Well, $http always returns a promise on both GET and POST. In your case, you need to do something with the data that comes back from your GET, so you're correctly using the promise's then() to run some code after the HTTP request finishes.

In your POST, it doesn't look like you care about the response, so you're simply choosing not to do anything. You could just as easily tack a then() onto your POST as well for any number of reasons.

Also, promises chain, so then() also returns a promise. Whatever code calls getAll() and addThis() can do something with the promise too. However, something that does getAll().then(function(data) { ... }) will have the data from the HTTP response passed to it because of the return resp.data you have up there.

Code that does addThis().then(function(data) { ... }), in this case, will have the entire HTTP response passed to it since there's nothing processing it like in getAll().

Upvotes: 3

BlackHatSamurai
BlackHatSamurai

Reputation: 23493

Because when you GET you are going to return a response which generally requires the request to wait for some sort of response. POST you don't necessarily need to wait for a response. As a note, just because you don't "need" a promise on a POST doesn't mean you can't have one. You could add one if you so desire.

Upvotes: 1

Related Questions