PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 11, 2022

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

 October 11, 2022     api, axios, javascript, reactjs     No comments   

Issue

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?


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


Answered By - abolfazl shamsollahi
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing