我有一个代码,其中我为每个 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
关于javascript - 出错后继续订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40587900/