0

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

YOUNG MIN CHO
  • 253
  • 1
  • 3
  • 13
  • 2
    since network requests are asynchronous, you can't - but I believe you're misusing the word "synchronously" - I think you mean "serially" ... you'd use Promises like they should be used .... `.then` ... and your getPost? functions would `return axios`, so that you can use `.then` on the returned Promise ... – Bravo Mar 30 '22 at 07:09
  • Your condition "without modifying getPost1 getPost2 and getPost3??" makes this impossible. Those function would have to `return axios.get(...)` - then you could use `.then` or `await` on it. – b2m9 Mar 30 '22 at 07:43
  • 1
    Btw [putting `.catch(err => console.error(err))` *everywhere* is discouraged](https://stackoverflow.com/q/50896442/1048572). Handle errors in a single place only. – Bergi Mar 30 '22 at 08:48

1 Answers1

2

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);
    })
}
Ji aSH
  • 3,206
  • 1
  • 10
  • 18
  • My intention was to call functions sequentially, but there was a mistake in my expression. I edited the question for people who need your answer. – YOUNG MIN CHO Mar 31 '22 at 00:50