Question

I am getting an error almost like my .then is firing before my async call is finished. I realize I am looping for the api post, but i am currently only trying it with an array size of 1.

Service:

this.saveTags = function (tag) {
        $http({
            method: "POST",
            url: '/api/projects/' + data.Id + '/tags',
            data: ({ Name: tag.Name })
        }).then(function (response) {
            console.log(response.data)
            if (typeof response.data === 'object') {
                return response.data;
            } else {
                // invalid response
                return $q.reject(response.data);
            }
        }, function (response) {
            // something went wrong
            return $q.reject(response.data);
        });

Controller:

 tags.forEach(function(tag) {
            counter++;
            data.saveTags(tag).then(function(data) {
                console.log(data)
            });
        });

Error:

enter image description here

Was it helpful?

Solution

You need to return a promise from the function that is resolved or rejected when the $http POST request is finished.

It looks like instead you're trying to return the reject and resolve products from the $http function itself, while your saveTags function ends up returning nothing to its caller (ie. from your forEach loop).

Try this:

this.saveTags = function (tag) {
    var deferred = $q.defer();

    $http({
        method: "POST",
        url: '/api/projects/' + data.Id + '/tags',
        data: ({ Name: tag.Name })
    }).then(function (response) {
        console.log(response.data)
        if (typeof response.data === 'object') {
            deferred.resolve(response.data);
        } else {
            // invalid response
            deferred.reject(response.data)
        }
    }, function (response) {
        // something went wrong
        deferred.reject(response.data)
    });

    return deferred.promise;
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top