Rxjs:重试承诺?

时间:2017-01-26 15:01:56

标签: javascript rxjs rxjs5

不知道为什么我的承诺正在解决,但试图重试。

var getResultsStream = url => Rx.Observable.onErrorResumeNext( 
     Rx.Observable.defer( () => Rx.Observable
        .fromPromise( getSearchResults(url)
        .catch(error => Rx.Observable.of(`Error: ${error}`)) )
        .timeout(20000, new Error(`Timeout: ${url}`))
     )
     .do( e => console.log(`Retrying: ${url}`))
     .retry(3)
)

这是一次更好的方式来重试承诺3次吗?

1 个答案:

答案 0 :(得分:2)

除非您对defer和/或onErrorResumeNext有特殊用途,否则您可以全力以赴,只需使用:



const request = url => Rx.Observable.of(url)
        .do(url => console.log("requesting: " + url))
        .switchMap(url => Rx.Observable.fromPromise(getSearchResults(url)))
        .timeout(20000, new Error(`Timeout: ${url}`))
        .retry(3);

request("http://foobar.com").subscribe(console.log, console.error);

function getSearchResults(url) {
  // simulating request-error
  throw new Error("Could not reach: " + url);
}

<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.10/dist/global/Rx.umd.js"></script>
&#13;
&#13;
&#13;