Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - Get response from axios with await/async

I'm trying to get JSON object from axios

'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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This seems to be one of those cases where async/await doesn'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 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...