gpt4 book ai didi

javascript - 使用es6promise顺序进行远程调用

转载 作者:行者123 更新时间:2023-11-28 18:14:59 25 4
gpt4 key购买 nike

我正在尝试使用 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,为什么这段代码不按顺序?

最佳答案

下面将按顺序调用代码,这是因为我们使用 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);
    });

关于javascript - 使用es6promise顺序进行远程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40875742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com