【问题标题】:use es6promise to make remote call sequentially使用 es6promise 顺序进行远程调用
【发布时间】:2017-04-14 00:44:52
【问题描述】:

我正在尝试使用 es6 promise ,依次进行两个远程调用, 这是我的代码

recordsCount(){
        let classInstance=this;
        let stateIns=this.state;
        return axios.post('/api/projectDocs/count',stateIns.gpSearch).then((response)=>{
            stateIns.totalRecords=response.data;
            classInstance.setState(stateIns);
        });

    }


loadGpDocs(start, end){
        let classInstance=this;
        let stateIns=this.state;
        stateIns.gpSearch.start=start;
        stateIns.gpSearch.end=end;
        return axios.post('/api/projectDocs/search',stateIns.gpSearch).then((response)=>{
            stateIns.data.gpDocs=response.data;
            classInstance.setState(stateIns);
        });
    }

调用这两个函数的代码

classInstance.recordsCount().then(classInstance.loadGpDocs(0, 20).then(function () {
                stateIns.ready = true;
                classInstance.setState(stateIns);
            }));

首先调用记录计数,这会返回一个 axios promise ,然后加载数据,这个返回 axios promise 然后将更改应用到 UI。

我遗漏了一些东西,调用不按顺序,请帮助我理解promise,为什么这段代码不按顺序?

【问题讨论】:

    标签: javascript reactjs es6-promise axios


    【解决方案1】:

    下面会依次调用代码,这是因为我们使用promise chaining来实现“阻塞”。由于所有返回的 Promise 最初都以 pending 状态开始,因此每个 Promise 都将被适当地等待,并且下一个 Promise 不会被调用,直到该 Promise 处于 fulfilled 状态之前。

    它将按以下顺序执行

    1. 致电recordsCount() 并更新stateIns.totalRecords
    2. 致电loadGpDocs() 并更新stateIns.data.gpDocs
    3. 更新stateIns.ready

      return classInstance.recordsCount()
        .then(() => {  // Wait for recordsCount() to be fulfilled
          // Notice that we are returning this promise
          // the next then() will wait until loadGpDocs is fulfilled
          return classInstance.loadGpDocs(0, 20);
        })
        .then(() => {
          stateIns.ready = true;
          classInstance.setState(stateIns);
        });
      

    【讨论】:

      【解决方案2】:

      问题是loadGpDocs(0, 20) 被称为在承诺链之外

      您可以通过以下方式解决它:

      classInstance.recordsCount()
        .then(classInstance.loadGpDocs.bind(classInstace, 0, 20))
        .then(function () {
             stateIns.ready = true;
             classInstance.setState(stateIns);
         }));
      

      注意classInstance.loadGpDocs.bind(classInstace, 0, 20) 正在返回一个函数 应用了它的参数没有调用它,所以只要recordsCount() promise 完成,它就会在promise 链中执行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-07
        • 1970-01-01
        • 1970-01-01
        • 2014-02-09
        • 2011-05-03
        • 1970-01-01
        • 2012-04-17
        • 2015-06-25
        相关资源
        最近更新 更多