I need to make function syncCalltest which call axios functions sequentially.
Is there any way to make syncCallTest function run sequentially without modifying getPost1 getPost2 and getPost3??
function syncCallTest() {
conole.log('before getPost');
getPost();
conole.log('after getPost and before getPost2');
getPost2();
conole.log('after getPost2 and before getPost3');
getPost3();
conole.log('after getPost3');
}
function getPost() {
axios get("http://example.com/posts/12345/")
.then(reponse => {
console.log(response);
})
.catch(error => {
console.error(error);
})
}
function getPost2() {
axios get("http://example.com/posts/12345/")
.then(reponse => {
console.log(response);
})
.catch(error => {
console.error(error);
})
}
function getPost3() {
axios get("http://example.com/posts/12345/")
.then(reponse => {
console.log(response);
})
.catch(error => {
console.error(error);
})
}
CodePudding user response:
Since your calls are Promise, I dont think you can make then synchronous.
But it seems that what you need is to have the call sequentially, then this is easy ;)
Change the postX methods so that they return their promise and then cascade the promises
function syncCallTest() {
getPost()
.then(getPost2)
.then(getPost3);
}
function getPost() {
return axios.get("http://example.com/posts/12345/")
.then(reponse => {
console.log(response);
})
.catch(error => {
console.error(error);
})
}
function getPost2() {
return axios.get("http://example.com/posts/12345/")
.then(reponse => {
console.log(response);
})
.catch(error => {
console.error(error);
})
}
function getPost3() {
return axios.get("http://example.com/posts/12345/")
.then(reponse => {
console.log(response);
})
.catch(error => {
console.error(error);
})
}