[英]Before resolving the promise on service method,it goes to the main method's promise
我寫了如下所示的Angular Service。
getPropertyDetailsByUsingApiService.js
(function () {
appModule.service('getPropertyDetailsByUsingApiService', ['$http', function ($http) {
this.propertyDetails = function (token, number, street, county, zip) {
var endpointUrl = 'http://my.com/api/Matcher?Token=';
var url = endpointUrl + token + '&Number=' + number + '&Street=' + street + '&County=' + county + '&Zip=' + zip;
return $http.get(url).then(function (data) {
var result = data;
if (result.data[0].Status == 'OK') {
$http.get(endpointUrl + token + '&Krp=' + result.data[0].Result[0].KRP + '&County=' + county)
.then(function (finalData) {
return finalData;
});
}
});
};
}
]);
})();
這是消耗方法:
propertyForm.js
//to call Api
vm.callApi = function () {
var county = _.find(vm.counties, function (c) { return c.id == vm.property.countyId; });
var city = _.find(vm.cities, function (c) { return c.id == vm.property.address.cityId; });
getPropertyDetailsByUsingApiService.propertyDetails(vm.getMd5Hashbytes(), vm.property.address.streetNumber, vm.property.address.streetName,
county.name, city.zipCode).then(function (result) {
vm.propertyDetails = result;
});
};
問:這里的問題是在解決服務方法的promise之前,轉到主方法的promise。換句話說,在解決服務方法的第二個promise之前將其轉到調用方法的promise。您能告訴我問題出在哪里嗎?
您可以重寫:
return $http.get('url').then(function(r) => { return r;})
如:
var defer = $q.defer();
$http.get('url').then(function(r) => { defer.resolve(r);})
return defer.promise;
在通常情況下,這沒有任何意義,但是在特殊情況下,您可以使用此構造執行任何操作:
var defer = $q.defer();
if (smth) {
defer.resolve('test1');
} else {
$http.get('url').then(function(r) => {
if (smth2) {
defer.resolve(r);
} else {
$http.get(..., function(r) => {
defer.resolve(r);
})
}
})
|
return defer.promise;
因此,在服務的第一個承諾中,您不會返回第二個承諾,因此第一個承諾只會隨着方法完成而完成並解決,而不會等待第二個承諾。
return $http.get(url).then(function (data) {
var result = data;
if (result.data[0].Status == 'OK') {
//Add a return here
return $http.get(endpointUrl + token + '&Krp=' + result.data[0].Result[0].KRP + '&County=' + county)
.then(function (finalData) {
return finalData;
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.