我有一个代码,其中我为每个id发出ajax请求并在结果出现时对其进行处理.这是我的实际代码和jsfiddle的简单副本:
var ids = [1,2,3,4,5,6];
var ids$= (id) => {
return Observable.of(id);
};
var loadIds$= (id) => {
if(id == 4) return xhr('/echo/jsoneee/', {id: id});
return xhr('/echo/json/', {id: id});
};
Observable.from(ids)
.concatMap(id => Observable.forkJoin(ids$(id), loadIds$(id)))
.catch((err, caught) => {
//get the id for which loadIds Failed
//send the id to subscribe() and continue the subscription
return Observable.empty();
})
.subscribe(result => console.log(result))
但是现在我需要修改代码,以便如果发生错误,我将必须获取ajax请求失败的ID,然后继续订阅,就像什么都没有发生一样.我还不能做到这一点.非常感谢您的帮助.
解决方法:
我认为您可以通过在Observable.create(…)中正确发出正确的值来大大简化此操作:
function xhr(url, json) {
return Observable.create(function (observer) {
$.ajax({
url: url,
data: JSON.stringify(json),
success: function (response) {
observer.next([json.id, json]);
},
error: function (jqXHR, status, error) {
observer.next([json.id]); // <== Notice this
},
complete: function () {
observer.complete();
}
});
});
}
var ids = [1,2,3,4,5,6];
var ids$= (id) => {
return Observable.of(id);
};
var loadIds$= (id) => {
if(id == 4) return xhr('/echo/jsoneee/', {id: id});
return xhr('/echo/json/', {id: id});
};
Observable.from(ids)
.concatMap(id => loadIds$(id))
.subscribe(result => console.log(result));
这样您可以完全避免forkJoin().另请注意,catch()运算符会自动从其来源退订.该运算符旨在继续使用另一个Observable,因此在诸如您这样的情况下非常有用.
您当然可以使用:
.catch((error, caught) => {
return caught;
})
但是,这会导致重新订阅,因此从一开始就重新释放通常不希望的所有值.
还有onErrorResumeNext()运算符,它只是忽略错误,但这可能不是您想要的.
观看演示:https://jsfiddle.net/4f1zmeyd/1/
有点类似的问题:get new ticket then retry first request
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。