我正在尝试分配一个变量 - >从$ http请求中检索到的值。 但是,用于变量的代码首先执行,而不是在使用promise之后等待http请求。
我是棱角分明但我认为并且承诺'应该照顾好这个。 请建议!
from django.db.models.signals import post_save
@receiver(post_save, sender=Voucher)
def decrease_quota(sender, instance, created, *args, **kwargs):
if created:
instance.vc -= 1
instance.save()
答案 0 :(得分:0)
这就是我的工作,而且效果很好。
Service.getData("param1", $scope.otherParam).then(
function(data){
console.log(data.data); //hey there it is... :)
$scope.someOtherfunctionCallback(data.data);
}
).finally(function(){ console.log("finally done with that crap..."); });
我的服务:
angular.module('app')
.factory('Service',['$http','$q',function($http, $q){
var service={};
var getReportMenu = function(){
//console.log("getting menu...");
var defer = $q.defer();
$http({
method:'GET',
url:'http://localhost:8080/API/PATH',
cache:true,
dataType:'json'})
.then(
function successCallback(response){
defer.resolve(response);
},
function errorCallback(response){
//TODO: handle this elegantly later.
alert("Error!");
});
return defer.promise;
}
return { getReportMenu : getReportMenu }; //Just easy encapsulation.
}
});
答案 1 :(得分:0)
$q.all([one]).then(function(arr) {
$scope.providerinfo = arr;
console.log(arr[0].data[0].AREA);
$scope.image = arr[0].data[0].ProvImage;
$scope.items = [{
src: $scope.image,
sub: 'This is a <b>subtitle</b>'
}]
console.log($scope.image); * * // This gives output as my required answer but SECOND --> Executed Second**
},
function(err) {
}
).
finally(
function() {
//Nothing
})
console.log($scope.image); * * // This gives output as undefined FIRST --> Executed first**
$scope.items = [{
src: $scope.image,
sub: 'This is a <b>subtitle</b>'
}]
答案 2 :(得分:0)
你的第二个console.log()首先运行,因为它不在你的诺言中。
你在做什么
$scope.items = [{
src: $scope.image,
sub: 'This is a <b>subtitle</b>'
}];
$ scope.image尚未提供,因为尚未履行承诺。将此代码移到promise中,它应该可以正常工作。
var one = providerdetailservice.getdetails($scope.whichProv);
$q.all([one]).then(function(arr){
$scope.providerinfo = arr;
console.log(arr[0].data[0].AREA);
$scope.image = arr[0].data[0].ProvImage;
console.log($scope.image);
//now try and access $scope.image
$scope.items = [{
src: $scope.image,
sub: 'This is a <b>subtitle</b>'
}];
}, function(err){}
).finally(function(){ //Nothing });