如何保证响应与请求的处理顺序相同

时间:2019-12-04 10:33:51

标签: axios

作为对点击处理程序的响应,我目前执行:

axios.get("http://whatever.com/itemId").then(response => {
  console.log(response);
});

从理论上讲,用户可能会连续非常快地单击几次。但是,我需要按照发出请求的顺序来处理响应,而且这些响应并非总是按顺序排列。

任何人都可以提供任何指针吗?

1 个答案:

答案 0 :(得分:0)

跟进以下内容,似乎效果很好。也许这样的事情应该成为图书馆本身的一部分。希望其他人觉得有用。


import axios from 'axios';

class OrderedAxios {  

  constructor() {
    this.promises = []
  }

  get(url) {
    var outsideResolve;
    var outsideReject;

    let promise = new Promise((resolve, reject) => {
      outsideResolve = resolve;
      outsideReject = reject;
    });

    promise.resolve = outsideResolve;
    promise.reject = outsideReject;

    this.promises.push(promise);

    axios.get(url)
      .then(response => {
        promise.response = response;                
        this.processPromises();
      })
      .catch(error => {
        promise.error = error;
        this.processPromises();
      })         

    return promise;
  }  

  processPromises() {            
    let continueProcessing = false;
    do { 
      continueProcessing = false;
      if (this.promises.length) {
        let promise = this.promises[0];
        if (promise.response || promise.error) {
          this.promises.shift();
          if (promise.response) {
            promise.resolve(promise.response);
          } else {
            promise.reject(promise.error);
          }
          continueProcessing = true;
        }
      }
    } while (continueProcessing);      
  }
}

export default OrderedAxios;