延迟$http.get 调用而不影响 angularjs 承诺



请注意,我已经阅读了所有与我的问题有些相关的StackOverflow问题,但这些问题都没有真正回答我的问题。请不要在没有完全理解我的问题之前将其标记为重复。

这是我的担忧:

我想延迟 angularJS $http.get 调用,而不会影响角度承诺。现在下面的代码在此行中抛出"angular-1.3.15.js:11655 TypeError:无法读取未定义的属性'then'":

updatePromise = promise.then(function(price)

这是我的部分代码:

MyAPP.service('FirstService', ['$q','$http', 'Constants', 'SecondService', 'UtilityService', function($q, $http, Constants, SecondService, UtilityService) {
var self = this;
var processFunction = function(AnArray) {
var updatedPromise;
var promises=[];
angular.forEach(AnArray, function(itemObj, index) 
{
var totalWorth = "";
if(itemObj.name != "")
{
var promise = SecondService.getPrice(itemObj.name);
updatedPromise = promise.then(function(price){
itemObj.price = price;
return itemObj;
}, function(error){
console.log('[+] Retrieving price has an error: ', error);
});
promises.push(updatedPromise);
}
else
{
console.log("Error!");
}
});
return $q.all(promises);
};
);

MyAPP.service('SecondService', ['$timeout','$http', 'Constants', function($timeout, $http, Constants) {
var self = this;
var URL = "/getPrice";
self.getPrice = function(itemName){
$timeout(function(){
var promise;
promise = $http({
url: URL,
method: 'POST',
data: {_itemName : itemName},
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
return response.data;
}, function(response) {
console.log("Response: " + response.data);
return response.data;
});
return promise;
}, 3500);
console.log("[-]getPrice");
};
}]);

请注意,processFunction 实际上应该返回一个承诺数组,因为其他函数需要这样做。

您的帮助将不胜感激!

如有进一步的问题/澄清,请告诉我。

谢谢!

$timeout返回一个 promise,因此您可以返回该 promise,然后从$http返回 promise :

self.getPrice = function (itemName) {
return $timeout(3500).then(function () {
return $http({
url: URL,
method: 'POST',
data: { _itemName: itemName },
headers: { 'Content-Type': 'application/json' }
});
}).then(function (response) {
return response.data;
}, function (response) {
console.log("Response: " + response.data);
return response.data;
});
};

最新更新