RxJS retry operator with ajax call

Deadly 提交于 2019-12-11 10:48:58

问题


I'm trying to figure out why my use of retry is not working in this example: http://jsbin.com/bobecoluxu/edit?js,output

var response$ = Rx.Observable.fromPromise(
  $.ajax({
    url: 'http://en.wikipedia.org/w/api.php',
    dataType: 'jsonp',
    data: {
      action: 'opensearch',
      format: 'json',
      search: term
    }
  }))
.retry(3);

I've wrapped the ajax call in an Observable in the searchWikipedia function, but if I try to force the failure of this call by turning off the wifi or throwing an exception by the related operator it simply doesn't work.

Thanks in advance!


回答1:


When you pass a promise to fromPromise and call retry, it will simply keep emitting the same Promise (ie subsequent HTTP requests won't be made).

If you pass a function that returns a Promise to fromPromise, that function will be re-invoked (allowing subsequent HTTP requests to be sent upon failure). The following example illustrates this:

const makesPromise = () => {
    console.log('calling');

    // Purposefully reject the Promise. You would return the return value
    // of your call to $.ajax()
    return Promise.reject();
};

const stream = Rx.Observable.fromPromise(makesPromise).retry(3);

stream.subscribe(log);

// >> calling
// >> calling
// >> calling
// Finally throws an uncaught error

Note: I had to update to the latest 4.x release of RXJS to use this feature



来源:https://stackoverflow.com/questions/36073058/rxjs-retry-operator-with-ajax-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!