AngularJS:使用回调和承诺

use*_*960 4 javascript promise angularjs

我无法将我的大脑包围在异步请求的概念中.

我有一个控制器用于我的视图,它是从提供者创建一个对象实例:

va.controller('VaCtrl',function($scope,$shipment){
    $scope.shipment = $shipment.Shipment();    
});
Run Code Online (Sandbox Code Playgroud)

提供者:

Shipment.provider('$shipment',function(){

    this.$get = function($http){

        function Shipment(){

        }

        Shipment.prototype.fetchShipment = function(){
            var shipment = undefined;
                $http.post('../sys/core/fetchShipment.php',{
                        // some data to POST
            }).then(function(promise){
                    shipment = promise.data;
                });

            return shipment;
        };

        return {
            Shipment: function(){
                return new Shipment();
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我的目标是从Shipment.prototype.fetchShipment()我的控制器内部访问数据.我的方法:

$scope.fetchShipment = function(){
       var shipment = $scope.shipment.fetchShipment();
        console.log(shipment); // undefined
};
Run Code Online (Sandbox Code Playgroud)

但是,这将返回undefined.

我读了大约$ q,延期,承诺和回调,现在我就像WTF; 我想要做的就是将检索到的数据推送到我的控制器,这样做的最佳方法是什么?

Aja*_*wal 5

你应该修改你的代码,如下所示直接从fetchshipment返回promise,然后在你的控制器中使用then().

Shipment.prototype.fetchShipment = function(){

    return $http.post('../sys/core/fetchShipment.php',{
        // some data to POST
    })
};


$scope.fetchShipment = function(){
    var shipment = $scope.shipment.fetchShipment().then(function(data){;
        console.log(data);
    });
};
Run Code Online (Sandbox Code Playgroud)

代码说明:

调用$ http将返回从服务器获取数据时解析的promise.在上面的代码中,我从服务函数返回$ http.post,它返回一个promise.因此,在控制器中,您正在等待承诺得到解决,并且当承诺得到解决时,结果将记录到控制台.

阅读有关角度的更多承诺文档: