为什么第二个console.log
在第一个打印实际数据时给我未定义?如何将promise中收到的数据分配给任何变量,以便能够在没有承诺的情况下使用它?
angular.module('dopasujApp')
.controller('productLoader', [ '$scope','getProducts',
function ($scope,getProducts) {
$scope.recived = {};
console.log($scope.list);
function getter() {
return getProducts(1, 150, 20, 'ASC', 'PRODUCT_ID', 'a').then(function (recived) {
$scope.recived = recived;
console.log($scope.recived);
}
);
}
getter();
console.log($scope.recived);
}
]);
这是我的工厂代码:
angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
return function(fit = 1, limit = 150, vendor = 20, sort = 'ASC', orderBy = 'PRODUCT_ID', search='a', size=[], filters={}, attribs=[]) {
var getProduct = {}, recived = {}, APIurl;
getProduct.data={};
getProduct.data.sort=sort;
getProduct.data.orderBy=orderBy;
getProduct.data.search=search;
getProduct.data.filters=filters;
getProduct.data.filters.ATTRIBS=attribs;
getProduct.data.filters.SIZE=size;
recived.list= [];
recived.count = 0;
recived.filters = {};
APIurl = "*******?action=getListing&fit="+fit+"&limit="+limit+"&vendor="+vendor;
var request = $http({
method: "POST",
url: APIurl,
headers: {
'Content-Type': 'application/json'
},
data: {
data: getProduct.data
}
});
var values = request.then(function (response){
return {
list: response.data.QUERY,
count: response.data.COUNT,
filters: response.data.FILTERS
};
});
return values;
}
}]);
答案 0 :(得分:3)
因为你的getProducts是一个承诺,甚至很难你的第二个console.log在你的getter();之后,在你的promise被解决之前执行console.log,这就是为什么它未定义。