0

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?

Nyi Nyi Hmue Aung
  • 587
  • 1
  • 7
  • 19

3 Answers3

1

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()
}
  • That would mean that the function ``` getUsers``` will have to accept a function as an argument. Is there any other way to know if the response is back inside the function ```doSomethingWhenrequestIsFinished ```? Anyway, thanks for the answer and this is already good enough. Thanks for the help – Nyi Nyi Hmue Aung Oct 11 '22 at 12:22
  • you can use promises too – abolfazl shamsollahi Oct 11 '22 at 12:26
1

Here I found one the way callback hell

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

axios({...})
.then(res => {
// Request is finished
callback({sucess:true})
})
.catch(err => {
callback({sucess:false})
})
}
 
const doSomethingWhenrequestIsFinished =()=> {
  getUsers(api , (response)=>{
    if(response.sucess){
    handleDoSomething()
    }
  })

  // Execute the rest of the code only after the response is back
}
Kiddo
  • 139
  • 9
1

If you're ok with using "Await/async" then this can be really simple and readable.

const getUsers = async function () {
  // Request goes here

  let result = await axios("http://google.com");
  return result.data;
};

const doSomethingWhenrequestIsFinished = async function(){
  let userData = await getUsers()

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

Note the use of "async" before each function. By using "Await" in an async function you essentially won't run the next line of code in that function until that request is completed.

Brandon
  • 389
  • 1
  • 8