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

Time:10-11

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?

CodePudding user response:

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

CodePudding user response:

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
}

CodePudding user response:

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.

  • Related