Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to know if the sending request is finished inside a function?

I have a function which sends http request to the server and I am calling it. I want to do some actions when the request inside that function is finished. How do I know if it’s done?

const getUsers =()=> {
  // Request goes here

axios({...})
.then(res => {
// Request is finished
})
.catch(err => {})
}
 
const doSomethingWhenrequestIsFinished =()=> {
  getUsers()

  // Execute the rest of the code only after the response is back
  handleDoSomething()
}

I am using React and I don’t want to use useState to keep track of the request state. How else can I know if the response is back or not?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can do it by using callback

const getUsers =(callback)=> {
  // Request goes here

axios({...})
    .then(res => {
       // Request is finished
       callback()
    })
    .catch(err => {})
}
 
const doSomethingWhenrequestIsFinished =()=> {
  getUsers(()=>{
     //the code you want to execute when request is done
  })

  
  handleDoSomething()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading