代码之家  ›  专栏  ›  技术社区  ›  Noitidart

重复前面的可观察到的

  •  -1
  • Noitidart  · 技术社区  · 6 年前

    我有一个函数返回一个承诺。我想捕捉这个错误,然后指数式地等待更长的时间,然后重试。但现在我只是在等一个常数5。这是我的代码:

    from(connectSocket()).pipe(
        catchError(e => {
            console.log('got error!', e.message);
            return timer(5000).pipe(
                tap(() => console.log('will repeat connect now')),
                repeat(1)
            );
        }),
        tap(() => setIsConnected.next(true))
    );
    

    然而,它不会重复。

    https://stackblitz.com/edit/rxjs-g7msgv?file=index.ts

    0 回复  |  直到 6 年前
        1
  •  1
  •   kos    6 年前

    要进行指数重试,您需要使用 retryWhen . 举个例子:

    // will retry with
    // 0, 10, 40, 90, 160 ms delays
    retryWhen(error$ =>
      error$.pipe(
        delayWhen((_, i) => timer(i * i * 10))
      )
    )
    

    exponential backoff

    Try this code in a playground

    在你的例子中你是 重复 timer ,而不是 from(connectSocket()) . 所以替代 catchError 用一个 得到你需要的东西。

    希望这有帮助

    此外,还有第三方工具可以添加指数退避,例如。
    https://github.com/alex-okrushko/backoff-rxjs

    看我的 "Error handling in RxJS"