繁体   English   中英

使用 await/async 从 axios 获取响应

[英]Get response from axios with await/async

我正在尝试从 axios 获取 JSON object

'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

这似乎是async/await不会给你带来太多async/await情况之一。 您仍然需要从异步函数返回结果,该函数将向调用者返回一个promise。 你可以这样做:

 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> 

这不是你想听到的,而是

Async/Wait 的工作原理是“无论在维加斯发生什么 - 留在维加斯”。 这意味着您无法传递在异步块之外使用阻塞 IO 调用的好处。

如果你想使用 async/await 来创建某种阻塞 IO 调用,它就不会工作,除非块调用者也在异步函数中,这通常不是这种情况。

async/wait 只有在你想要有一个很长的 IO 调用链时才有用,但整个链仍然必须是非阻塞的。 链内的单个调用可能会阻塞,但完整的链不会。

例子

async fn(url) { //this is a non blocking function
   let res = await axios.get("http://jsonservice1"); //blocking but only inside this function
   let res2 = await axios.get(url+'?s='+res.data);//res.data is resolved already
   return res2; //this how it returns results but it will not be resolved until .then is called what is effectively a callback 
}
fn("google.com").then(R=>console.log('sorry I am not blocking '+R.data));

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

我认为你对javascript中的promise和async / await没有正确理解。 请尝试这样:

function getData(url, method) {
    var ip = location.host;
    return axios({
        url: url,
        method: method,
        timeout: 8000,
        headers: {
            'Content-Type': 'application/json',
        }
    })
}

let dataObj;
let url = http() + ip + '/getData', method = 'post';
getData(url, method)
.then(function (result) {
    console.dir(result);
    dataObj = result;
})
.catch(function(error){
    console.log(error);
});

异步/等待:

function getData(url, method) {
    var ip = location.host;
    return axios({
        url: url,
        method: method,
        timeout: 8000,
        headers: {
            'Content-Type': 'application/json',
        }
    })
}
(async function(){
    let dataObj;
    let url = http() + ip + '/getData', method = 'post';
    try{
        const result = await getData(url, method);
        dataObj = result;
    } catch (error) {
        console.log(error);
    }
})();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM