Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

reactjs - how to return response of axios in return

I want to return the response of axios but always the response that returned is undefined:

wallet.registerUser=function(data){
axios.post('http://localhost:8080/register',{
phone:data.phone,
password:data.password,
email:data.email
}).then(response =>{
  return response.data.message;
  console.log(response.data.message);
}).catch(err =>{
  console.log(err);
})
}

console.log(wallet.registerUser(data));

The console always logs as undefined. Is their any way returning this response.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

console.log won't wait for the function to fully complete before logging it. This means that you will have to make wallet.registerUser asynchronous, there are two main ways to do this:

  1. Callback - this is when you pass a function as a parameter into your existing function which will be executed once your axios call has finished. Here is how it would work with your code:

    wallet.registerUser=function(data, callback){
      axios.post('http://localhost:8080/register',{
        phone:data.phone,
        password:data.password,
        email:data.email
      }).then(response =>{
        callback(response.data.message);
        console.log(response.data.message);
      }).catch(err =>{
        console.log(err);
      })
    }
    
    wallet.registerUser(data, function(response) {
      console.log(response)
    });
    
  2. Promise - The easiest way to do this is to put async in front of your function name. This will make anything returned from the function return in the form of a promise. This is how it would work in your code:

     wallet.registerUser=async function(data){
      axios.post('http://localhost:8080/register',{
        phone:data.phone,
        password:data.password,
        email:data.email
      }).then(response =>{
        return response.data.message;
        console.log(response.data.message);
      }).catch(err =>{
        console.log(err);
      })
    }
    
    wallet.registerUser(data).then(function(response) {
      console.log(response);
    });
    

Here is some more information on asynchronous functions:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...