简体   繁体   English

带有ajax调用的RxJS重试运算符

[英]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我想弄清楚为什么我的重试使用在这个例子中不起作用: 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.我已经将 ajax 调用封装在 searchWikipedia 函数中的 Observable 中,但是如果我试图通过关闭 wifi 或相关操作员抛出异常来强制此调用失败,它根本不起作用。

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).当您将承诺传递给fromPromise并调用重试时,它只会继续发出相同的承诺(即不会发出后续 HTTP 请求)。

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).如果您将一个返回 Promise 的函数传递给fromPromise ,该函数将被重新调用(允许在失败时发送后续 HTTP 请求)。 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注意:我必须更新到最新的 RXJS 4.x 版本才能使用此功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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