我有一個物品數組,我將從localStorage獲得。在AngularJS中有條件地創建一個承諾
var items = JSON.parse($window.localStorage.selectedResources)['server'];
var arr = [];
var idsArray = [];
angular.forEach(items, function (item) {
idsArray.push(item.id);
});
然後我火API調用...
//Make the API call
ds.getBillInfo(idsArray)
.then(function(response){
var serversList = [];
for (var key in response) {
// iterate over response
的問題是,如果項目數組是空的,所以做了idsArray
。 然後錯誤說Cannot read property 'then' of undefined
。
我想要做的是even if the idsArray is empty , I want lines to execute inside the then block thinking as there is no promise
。
我該怎麼做?
編輯
如果我做$q.all([ds.getBillInfo(idsArray)])
那麼就沒有錯誤。
的getBillInfo()
樣子:
this.getBillInfo = function(idsArray){
if(!idsArray.length) return;
var segmentUrl = '';
for(var i =0;i<idsArray.length;i++){
if(i != (idsArray.length-1))
segmentUrl += 'ids='+idsArray[i]+'&';
else
segmentUrl += 'ids='+idsArray[i];
}
return HttpWrapper.send('/api/bill?bill=t&'+segmentUrl, {"operation": 'GET'});
};
您需要修改'getBillInfo'總是返回一個承諾 – SLaks
東西是不正確這裏...喜歡@SLaks說。 – Pytth
...即使返回類似'Promise.reject('empty')'的東西也會工作,並且最終會在catch或Promise.resolve()中解析 – adeneo