问题
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