Why does Axios (with async/await) return a full promise?

Viewed 21071

I have a problem with async/await. Here is my code:

import axios from 'axios'

export default async function getRequestedData (requestAddress, params) {
   return await axios.get(requestAddress, {params: params})
}

But instead of the result it returns a full promise, so the data is heavily nested inside a promise:

enter image description here

5 Answers

One liner:

return (await axios.get(url)).data;

In React component you can do with this trick:

function InitProduct() {
    // Get your product from database
    var productId = 'abc';
    axios.get('/api/products/' + productId).then(response => {
        $('.' + productId).text(response.data.ProductTitle);
    });

    return (<div className={productId}></div>)
}

export class TestNow extends Component {
    render() {
        return (
            <div>
                {InitProduct()}
            </div>
        )
    }
}

An async function will always wrap what it returns in a promise so you should chain the caller with a then() method thereby resolving that promise for example: getRequestedData (requestAddress, params).then ( (data) => { ...do something... });

Or you could await the call to getRequestedData function, in which case the data inside the returned promise would be extracted for example:

let requestedData = await getRequestedData (requestAddress, params):
Related