gpt4 book ai didi

javascript - 在 AngularJS 中有条件地创建 promise

转载 作者:行者123 更新时间:2023-11-29 19:02:03 28 4
gpt4 key购买 nike

我有一个要从 localStorage 获取的项目数组。

                   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

问题是如果 items 数组为空,idsArray 也为空。然后错误显示 Cannot read property 'then' of undefined

我想做的是即使 idsArray 为空,我也希望行在 then block 内执行,因为没有 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 中用新的 Promise 包装您的逻辑并在空数组上解析它。

类似于:

self.getBillInfo = function(array){

var deferred = $q.defer();

if(array.length == 0){
deferred.resolve([]); // return empty list
}
else{
var segmentUrl = '';
for(var i =0;i<idsArray.length;i++){
if(i != (idsArray.length-1))
segmentUrl += 'ids='+idsArray[i]+'&';
else
segmentUrl += 'ids='+idsArray[i];
}
HttpWrapper.send('/api/bill?bill=t&'+segmentUrl, {"operation": 'GET'})
.then(function (response) {
deferred.resolve(response.data);
}
, function (error) {
deferred.reject(error);
});

}

return deferred.promise;
}

[编辑]

关于 @JC Ford 点,因为 HttpWrapper 返回 Promise 我们可以用不同的方式编写上面的逻辑:

self.getBillInfo = function(array){

if(array.length == 0){
return $q.resolve([]); // return empty list;
}
else{
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'});
}
}

关于javascript - 在 AngularJS 中有条件地创建 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46244943/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com