错误后继续订阅 [英] Continue the subscription after error

查看:188
本文介绍了错误后继续订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,其中每个id我正在制作ajax请求并处理结果。这是我的实际代码的简单副本和 jsfiddle

I have a code where for each of the ids I am making an ajax request and processing them as results come in. Here is a simple replica of my actual code and 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 然后继续订阅就像什么都没有发生了。我还没能做到这一点。非常感谢帮助。

But now I need to modify the code so that if an error occurs I will have to get the id for which the ajax request failed and then just continue the subscription like nothing happened. I have not been able to do this yet. Help is really appreciated.

推荐答案

我认为您可以通过在 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,因此它在您的情况下非常有用。

This way you can avoid forkJoin() completely. Also be aware that catch() operator automatically unsubscribes from its source. This operator is intended to continue with another Observable so it's now very useful in cases such as yours.

您当然可以使用:

.catch((error, caught) => {
    return caught;
})

然而,这会导致重新订阅,从而从一开始就重新发布所有值,这通常是不受欢迎的。

This however causes resubscription and thus reemission of all values from the beginning which is usually undesired.

还有 onErrorResumeNext()运算符,它只是忽略了错误,但这可能不是你想要的。

There's also onErrorResumeNext() operator that simply ignores the errors but that's probably not what you want.

参见演示: https://jsfiddle.net/4f1zmeyd/1/

一个稍微类似的问题:获取新票然后重试第一次请求

A slightly similar question: get new ticket then retry first request

这篇关于错误后继续订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆