簡體   English   中英

如何延遲重試以使用RxJS5發送HTTP請求?

[英]How to delay retrying to send an HTTP request with RxJS5?

我遇到了使RxJS5可觀察流以我想要的方式運行的問題。

該流應該使用axios向網站發送HTTP請求,如果響應是HTTP錯誤(axios強制導致JavaScript錯誤),則可觀察序列應等待10毫秒,然后嘗試重新發送請求(由於某種原因)我正在發送請求的網站在您重試立即發送請求並且不斷拋出錯誤時不喜歡它,但大多數情況下延遲10毫秒表現良好)。

Rx.Observable
  .fromPromise(axios('http://example.com/12345'))
  .map(x => new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(x)
    }, 2000)
  }))
  .debounceTime(2000)
  .do(console.log)
  .retry(10)
  .subscribe(console.log, console.error)

我在Codepen上有一些示例,只是做了一些更改,以使其更加明顯,流如何工作: http ://codepen.io/leakyabstractions/pen/pNmvyZ?editors = 0010

我嘗試在.map()運算符的位置使用.delay() .debounceTime() .timer() .timeInterval().timeout() ,但沒有(包括.map() )有效。 我究竟做錯了什么?

所以基本上你要找的是“10ms后重試,但只有10次”? (這是你的retry(10)暗示的。我認為一個復雜的解決方案將包括重retryWhen在這里:

const mockedRestError$ = Rx.Observable.throw("http://example.com/12345");

// we'll start with an empty string, because otherwhise
// we could not log the "start..."
Rx.Observable.of("")
  .do(() => console.log("start..."))
  .switchMapTo(mockedRestError$)
  .retryWhen(tenTimesWithDelay)
  .subscribe(console.log, console.error, console.info); // is never called, because 


function tenTimesWithDelay(errors) {
  return errors
    .scan((count, err) => {
      ++count;
      // optionally to throw the error all the way down to the subscription
      // comment the throw out to have the stream simply complete
      if (count >= 10) {
        throw err;
      }
      return count;
    }, 0)
    .takeWhile(count => count < 10)
    .do(count => console.log(`Retry #${count} in 100ms...`))
    .delay(100);
}

這是代碼筆: http//codepen.io/anon/pen/bBydwZ?edit = 0010

還請注意,我將延遲設置為100毫秒而不是10毫秒,這樣它在控制台中顯示一點清潔。

olsn的回答是有效的,但是我想分享另一個我意外提出的解決方案,在我看來這更直接:

console.log('start')
Rx.Observable
// emit observable every 10 ms, change to a bigger number to observe results
.interval(10)
// start immediately
.startWith(0)
// do it 10 times
.take(10)
.do(x => console.log('emitting', x))
// for every observable emitted, do an HTTP request
.flatMap(() => new Promise((resolve, reject) => resolve('resolved promise')))
.first(x => !(x instanceof Error))
.subscribe(console.log, console.warn, () => console.info('done'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM