user884424 user884424 - 10 days ago 5
Javascript Question

use es6promise to make remote call sequentially

I am trying to use es6 promise , to make two remote calls in sequence,
here is my code

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);
});
}


code to call the two functions

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


first call the records count, this returns a axios promise , then load data, this return axios promise then apply changes to UI.

Iam missing something, calls are not in sequence, please help me understand promise, why this code is not following sequence?

Answer

The problem is that loadGpDocs(0, 20) is called outside of the promise chain

You could solve it by doing:

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

Notice that classInstance.loadGpDocs.bind(classInstace, 0, 20) is returning a function with its arguments applied without calling it, so it gets executed inside the promise chain whenever recordsCount() promise is done