2017-08-10 28 views
0

要返回返回未定义Axios公司,但总是响应的响应:我如何返回爱可信的响应回报

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)); 

控制台始终记录为未定义。他们以任何方式返回这个回应。

+0

的[我如何回报可能的复制来自异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

回答

3

console.log不会等待函数在记录之前完全完成。这意味着,你将不得不作出wallet.registerUser异步的,主要有两种方法可以做到这一点:

  1. 回调 - 这是当你将一个函数作为参数传入,将一次执行现有功能的axios呼叫已完成。下面是它如何与您的代码工作:

    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. 承诺 - 做,这是把async在函数名称前面的最简单方法。这将使从函数返回的任何东西以promise的形式返回。这是怎么会在你的代码工作:

    async 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); 
        }) 
    } 
    
    wallet.registerUser(data).then(function(response) { 
        console.log(response); 
    }); 
    

这里是异步函数的一些详细信息:

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

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

+0

这是正确的。控制台是同步的,Axios正在进行异步调用。 –