我有一个物品数组,我将从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