繁体   English   中英

如何确定承诺结果的优先级?

[英]how to prioritize promise results?

我正在开发一个React应用。 我需要使用api请求的结果更新状态。现在,应用程序功能使我不得不频繁发出api请求。 因此,一旦结果到达,我便在then()中设置状态。 但是某些结果比其他结果花费更多的时间。 因此,有时先前承诺的结果将设置状态而不是当前状态。 我如何确定承诺的优先级,以使最新请求结果设置状态。 或者,一旦我打电话给新的诺言,还有另一种方法摆脱先前的诺言吗?

this.state = {
      searchterm: '',
      isfocused: false,
      current: -1,
      noresults: false,
      // latest promise id
      reqseqid: 0,
      filteredList: []
    }


callingfunction(){
   let reqseqid = this.state.reqseqid + 1;
    this.setState({ 
      searchterm,
      filteredList: [],
      reqseqid
     });
    searchresults(searchterm, reqseqid)
      .then(res => {
        let { results, reqseqid } = res;
        console.log(reqseqid, this.state.reqseqid);
        if(reqseqid === this.state.reqseqid){
          if(res.length === 0){
            this.setState({ 
              current: -1,
              filteredList: [],
              noresults: true
             });
          }else{
            this.setState({ 
              current: -1,
              filteredList: results,
              noresults: false
            });
          }
        }

      });
}

我通常通过使用实例属性或类似的变量来处理此问题,异步回调可以检查该实例属性以查看其结果是否仍然需要或请求是否过时。 例如,在您的构造函数中:

this.ajaxSequence = 0;

然后提出您的要求:

const thisSequence = ++this.ajaxSequence;
doTheAjaxRequest()
    .then(result => {
        if (thisSequence == this.ajaxSequence) {
            // Use the result
        }
    })
    .catch(/*...probably check and ignore the error if this request was stale...*/);

它不一定是数字。 例如:

this.currentRequestPromise = null;

然后

const thisPromise = this.currentRequestPromise = doTheAjaxRequest()
    .then(result => {
        if (thisPromise == this.currentRequestPromise) {
            // Use the result
        }
    })
    .catch(/*...probably check here too...*/);

有很多方法可以做到这一点。 我更喜欢的一种方法是拥有一个对象实例( requestSequence ),该实例跟踪接收到的请求以及每个请求的递增索引值。 当一个请求/允诺的回报,检查是否该请求索引的索引是> =的largestIndex你已经从返回requestSequence 如果是,则返回该结果,并增加largestIndex 否则,请勿返回该值。

这种方法的好处是,此代码的调用者可以根据需要尽快发出请求,而requestSequence将确保顺序。 调用者将不必担心过期的请求或检查返回的值是否与当前输入匹配。

您应该查看执行流程中的可观察对象。 您正在寻找的是不同时拉平承诺流,这可以通过xstream的库轻松完成:

const xs = require("xstream").default;
const promise$ = ... // create a stream of promises
return promise$.map(p => xs.fromPromise(p)).flatten();

假设您需要定期获取,您可以轻松创建承诺流

const promise$ = xs.periodic(500).map(() => makeApiCall());

我强烈建议您朝这个方向看。 尝试直接处理组件生命周期中的promise不是一件容易的事,应该在Redux中间件(或其他状态管理实用程序)中完成。 例如,它要求您在Promise的回调中跟踪正在安装/卸载的组件的状态,否则您可能会对未安装的组件进行操作。 这也可能导致内存泄漏。

暂无
暂无

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

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