Javascript 使用 await/async 从 axios 获取响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49661209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:26:15  来源:igfitidea点击:

Get response from axios with await/async

javascriptasync-awaitaxios

提问by IgorM

I'm trying to get JSON object from 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);
    }
}

Now I need to fetch the res

现在我需要获取资源

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

The code is blocking and waits for the result, but I'm getting undefined instead of object

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

回答by Mark Meyer

This seems to be one of those cases where async/awaitdoesn't buy you much. You still need to return a result from the async function, which will return a promise to the caller. You can do that with something like:

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

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>

But in this example, since you don't need to do much in the actual function with the result, you're probably better off just returning axios's promise:

但是在这个例子中,由于你不需要在实际函数中用结果做太多事情,你可能最好只返回 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>

回答by Songgen

I think you didn't understand correctly about promise and async/await on javascript. Please try like this:

我认为您没有正确理解 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);
});

async/await:

异步/等待:

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