如何返回axios的响应作为回报 [英] how to return response of axios in return
问题描述
我想返回axios的响应,但是返回的响应始终是不确定的:
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.
推荐答案
console.log在记录功能之前不会等待该功能完全完成.这意味着您将不得不使wallet.registerUser
异步,有两种主要方法可以做到这一点:
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:
-
回调- 这是当您将函数作为参数传递给现有函数时,将在axios调用完成后执行该函数.这是与您的代码一起使用的方式:
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)
});
承诺-
最简单的方法是将async
放在函数名称的前面.这将使从函数返回的所有内容以promise的形式返回.这就是它在您的代码中的工作方式:
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/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/zh-CN/docs/词汇表/回调函数
这篇关于如何返回axios的响应作为回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!