使用 await/async 从 axios 获取响应

新手上路,请多包涵

我正在尝试从 axios 获取 JSON 对象

'use strict'

async function getData() {
    try {
        var ip = location.host;
        await axios({
            url: http() + ip + '/getData',
            method: 'POST',
            timeout: 8000,
            headers: {
                'Content-Type': 'application/json',
            }
        }).then(function (res) {
            console.dir(res); // we are good here, the res has the JSON data
            return res;
        }).catch(function (err) {
            console.error(err);
        })
    }
    catch (err) {
        console.error(err);
    }
}

现在我需要获取 资源

let dataObj;
getData().then(function (result) {
    console.dir(result); // Ooops, the result is undefined
    dataObj = result;
});

代码正在阻塞并等待结果,但我得到的是 undefined 而不是 object

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

阅读 637
2 个回答

这似乎是 async/await 不会给你带来太多好处的情况之一。您仍然需要从异步函数返回一个结果,该结果将向调用者返回一个承诺。你可以用类似的东西来做到这一点:

 async function getData() {
    try {
       let res = await axios({
            url: 'https://jsonplaceholder.typicode.com/posts/1',
            method: 'get',
            timeout: 8000,
            headers: {
                'Content-Type': 'application/json',
            }
        })
        if(res.status == 200){
            // test for status you want, etc
            console.log(res.status)
        }
        // Don't forget to return something
        return res.data
    }
    catch (err) {
        console.error(err);
    }
}

getData()
.then(res => console.log(res))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>

但在这个例子中,因为你不需要在实际函数中对结果做太多,你可能最好只返回 axios 的承诺:

 function getDataPromise() {
    return axios({
            url: 'https://jsonplaceholder.typicode.com/posts/1',
            method: 'get',
            timeout: 8000,
            headers: {
                'Content-Type': 'application/json',
            }
        })
       .then(res => res.data)
       .catch (err => console.error(err))
    }

getDataPromise()
.then(res => console.log(res))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>

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

来自 ajax,我更喜欢模块化方法。要发送的数据、成功函数和失败函数与使用 axios 的函数是分开的。下面的示例代码在后端根据用户名从 node.js 和 mysql 获取用户电子邮件。 ★

 HTML: <button onclick=" testaxios();">TestAxios</button>‎

浏览器中的JS:

 var data = {
  username: "myusername"
}
async function testaxios() {
  try {
    let res = await axios({
      method: 'POST',
      data: data,
      url: '/testmysql',

    });
    if (res.status == 200) {
      success(res);
    };
  }
  catch (error) {
    fail(error);
  };
}

function success(res) {
  console.log(res.data[0][0].email);
}
function fail(error) {
  console.log(error);
}

后端nodeJS中的JS:

 app.post("/testmysql", async function (req, res) {
try {
    let usrname = req.body.username;
    let em = await pool.query("SELECT email FROM users WHERE username = ?", usrname);
    res.send(em);

} catch (err) {
    console.log(err);
} });

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

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