简体   繁体   中英

RxJS retry operator with ajax call

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM