Axios 在控制台上打印值但返回未定义

som*_*guy 0 javascript axios

一段时间以来,我遇到了一个相当大的问题,并且让我很紧张,这没有意义。我在我的 React 前端使用了 axios,它在将 get 值分配给状态时效果很好。但是当在普通的 javascript 代码中使用它时,我似乎有以下问题:我可以在控制台中打印对象的值,但它只会返回 undefined .. 这是我的代码:

login = () => {
        let data;
        axios.get('https://myaddress/authenticate')
            .then(response => {
                data = response;
                console.log('data here', data);
            })
            .catch(error => {
                console.error('auth.error', error);
            });
        console.log('eee', data);
        return data;
    };
Run Code Online (Sandbox Code Playgroud)

这里我们严格地谈论 axios。

dar*_*ode 5

您无法返回 ajax 响应,因为它是异步的。你应该把你的函数包装成一个承诺或传递一个回调来登录

更新:正如@Thilo 在评论中所说,这async/await将是另一种选择,但它会让您设置对数据的响应...

1. 包装成承诺

 login = () => new Promise((resolve, reject)=>{
      axios.get('https://myaddress/authenticate')
      .then(response => {
           resolve(response)
      })
      .catch(error => {
           reject(error)
      });
 });

 // Usage example
 login()
    .then(response =>{
       console.log(response) 
    })
    .catch(error => {
       console.log(error)
    })
Run Code Online (Sandbox Code Playgroud)

2.传递回调

login = (callback) => {

   axios.get('https://myaddress/authenticate')
        .then(response => {
            callback(null,response)
        })
        .catch(error => {
            callback(error,null)
        });
};

// Usage example
login((err, response)=>{

     if( err ){
       throw err;
     }

     console.log(response);

})
Run Code Online (Sandbox Code Playgroud)

3. 异步/等待

login = async () => {

  // You can use 'await' only in a function marked with 'async'

  // You can set the response as value to 'data' by waiting for the promise to get resolved
  let data = await axios.get('https://myaddress/authenticate');

  // now you can use a "synchronous" data, only in the 'login' function ...
  console.log('eee', data);

  return data; // don't let this trick you, it's not the data value, it's a promise

};

// Outside usage
console.log( login() ); // this is pending promise
Run Code Online (Sandbox Code Playgroud)

  • 我只是担心它使它看起来比实际需要的更多样板(使回调解决方案看起来比应有的更有吸引力)。也许也提出“async/await”。OTOH,无论如何,这是一个骗局。 (2认同)