通过await/async获取axios的响应

Igo*_*orM 7 javascript async-await 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要获取res

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

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

Mar*_*yer 18

这似乎是那些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))
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
Run Code Online (Sandbox Code Playgroud)

但是在这个例子中,由于你不需要在结果的实际函数中做很多事情,你可能最好只返回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))
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
Run Code Online (Sandbox Code Playgroud)