AngularJS: Why is .then() not waiting for the promise object to arrive

我怕爱的太早我们不能终老 提交于 2019-12-14 03:59:34

问题


I have created the following angular service for the purpose of making the API calls.

(function (module) {
    module.service('APIService',function ($http, $q) {
        console.log("Reached APIService")
        var deferred = $q.defer();
        this.getData = function (requestURL) {
            console.log("Reached APIService @GET", requestURL);
            $http.get(requestURL).success(
                function (data, status) {
                    deferred.resolve(data);
                    console.log("In service",status,data);
                }).error(
                function (data, status) {
                    deferred.reject(data);
                    console.log(status);
                });
            return deferred.promise;
        };

        this.postData = function (requestURL, requestObj) {
            console.log("Reached APIService @POST", requestURL, requestObj);
            $http.post(requestURL, requestObj).success(
                function (data, status) {
                    deferred.resolve(data);
                    console.log(status);
                }).error(
                function (data, status) {
                    deferred.reject(data);
                    console.log(status);
                });
            return deferred.promise;
        };
    });
}(angular.module("MainApp")));

I have injected it in my two controllers. However, I am facing following issues:

  1. When I call it first time in first controller, it works fine and returns the desired result. However, when I call it in second controller as follows:

        APIService.getData(Config + headerURL).then(function (response) {
            console.log(Config + headerURL);
            console.log("header response from API", response);
    
        },function(error) {
            console.log("API call for header data failed");
        });
    

Since my service returns a promise object, I don't expect the code inside .then() to work before the service data arrives. However, it runs before service data arrives (no clue how). The most strange thing is that the response that I get inside .then() is not actually the response from this URL (Config+headerURL), but it is the response that was obtained from a different URL previously called in first Controller using the same APIService service.

Just to inform: the actual response from current URL do arrive at a later stage.

I am aware of asynchronous callings and I think it has something to do in this case, but I guess .then() handles it in Angular. So I am confused what is the issue here. Can anyone shed some light please?


回答1:


Since the service is a singleton, you only have a single instance of the deferred object.

Once resolved, it will keep being resolved, so the next time you call, getData, it will return immediately.

You could move:

var deferred = $q.defer();

inside both your getData and postData function.

Or you could just return the promise that $http creates.




回答2:


Just try this, You need to return to the http result.

this.getData = function (requestURL) {
            console.log("Reached APIService @GET", requestURL);
           return $http.get(requestURL) };



回答3:


Looks like you have to disable cache explicitly within $http call.

$http.get({
  url: requestURL,
  cache: false
})



回答4:


You are using an anti-pattern by creating your own promises when $http already returns a promise.

Get rid of $q altogether in this service and simply return $http

this.getData = function (requestURL) {
    console.log("Reached APIService @GET", requestURL);
    return $http.get(requestURL).then(function (response) {
        return response.data;
        console.log("In service", status, data);
    }, function () {
        // errror handling here
    });

};


来源:https://stackoverflow.com/questions/32718326/angularjs-why-is-then-not-waiting-for-the-promise-object-to-arrive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!