Get response from axios with await/async

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>

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:

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>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)