如何返回axios的响应作为回报

新手上路,请多包涵

我想返回 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));

控制台始终记录为未定义。他们是否以任何方式返回此响应。

原文由 Candy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 658
2 个回答

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

  1. Promise - 最简单的方法是将 async 放在你的函数名前面。这将使函数返回的任何内容都以 Promise 的形式返回。这就是它在您的代码中的工作方式:
     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);
   });

以下是有关异步函数的更多信息:

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

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

原文由 Showard180 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用承诺:

我是新来的,所以你可以给我建议来改进我的代码。

例如我想调用其他文件中的 checkVerified() 函数:

工具.js

 export function checkVerified(val, values) {
    return new Promise((resolve, reject) => {
        axios
            .get(`${getInitialServerUrl}/core/check_verified/${val}/`)
            .then(res => {
                resolve(res)
            })
            .catch(err => reject(err))
    })
}

我从另一个文件调用这个函数:

一些文件.js

 const handleSubmit = e => {
        e.preventDefault();
        checkVerified(values.mobile, props)
            .then(res => {
               console.log(res);
         })
        .catch(err => console.log(err.response))
    }

原文由 Nikhil Bhardwaj 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进