Javascript 使用es6promise按顺序进行远程呼叫
我正在尝试使用es6 promise,按顺序进行两次远程调用, 这是我的密码Javascript 使用es6promise按顺序进行远程呼叫,javascript,reactjs,es6-promise,axios,Javascript,Reactjs,Es6 Promise,Axios,我正在尝试使用es6 promise,按顺序进行两次远程调用, 这是我的密码 recordsCount(){ let classInstance=this; let stateIns=this.state; return axios.post('/api/projectDocs/count',stateIns.gpSearch).then((response)=>{ stateIns.totalRecords=resp
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承诺,然后加载数据,这将返回axios承诺,然后将更改应用到UI
我遗漏了一些东西,调用不按顺序进行,请帮助我理解promise,为什么此代码不按顺序进行?下面将按顺序调用代码,这是因为我们使用promise链接来实现“阻塞”。由于所有返回的承诺最初都是在
挂起
状态下开始的,因此每个承诺都将被正确地等待,下一个承诺将不会被调用,直到承诺达到履行
状态
它将按以下顺序执行
recordscont()
并更新stateIns.totalRecords
loadGpDocs()
并更新stateIns.data.gpDocs
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);
});
下面将按顺序调用代码,这是因为我们使用承诺链来实现“阻塞”。由于所有返回的承诺最初都是在
挂起
状态下开始的,因此每个承诺都将被正确地等待,下一个承诺将不会被调用,直到承诺达到履行
状态
它将按以下顺序执行
recordscont()
并更新stateIns.totalRecords
loadGpDocs()
并更新stateIns.data.gpDocs
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);
});
问题是
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)
在不调用它的情况下返回一个应用了参数的函数,因此每当recordscont()
promise完成时,它就会在promise链中执行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)
返回一个函数,该函数的参数应用了,而没有调用它,因此只要recordscont()
promise完成,它就会在promise链中执行