how to return response of axios in return

巧了我就是萌 提交于 2019-12-03 07:35:57

问题


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.


回答1:


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




回答2:


I used async and await methods and wrapped my axios call and function calling the axios call in these methods. I returned axios value as well as returned response object within it. I have shared the snippet in the below link.

Returning data from Axios API



来源:https://stackoverflow.com/questions/45620694/how-to-return-response-of-axios-in-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!