0

I've got a function that makes a call with axios and returns it:

const makeRequest = () => {
    return axios.get('/data');
}

const printResponse = () => {
    makeRequest()
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        console.log(error)
    })
}

I'm trying to use async await to make this better and avoid using 'then'.

const makeRequest = async () => {
    return await axios.get('/data');
}

const printResponse = () => {
    try {
        const response = makeRequest();
        console.log(response)
    } catch(error) {
        console.log(error)
    }
}

However, despite using await, makeRequest still returns a promise, so I have to end up using then in my printResponse function anyway. Am I not using this correctly?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Human Cyborg Relations
  • 1,202
  • 5
  • 27
  • 52
  • 2
    async will always return a promise, btw have you tried to delete async and await from make request and add them into print response in order to have response = await makeRequest()? – Benjamin Barbé Jun 28 '20 at 23:25
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Emile Bergeron Jun 28 '20 at 23:43

1 Answers1

4

"However, despite using await, makeRequest still returns a promise"

Yes, of course it does. async/await is just syntactic sugar for working with Promises. In particular, any function marked async will return a Promise - this is by design.

If you don't like using .then, you can just as easily use async/await to consume this promise:

const printResponse = async () => {
    try {
        const response = await makeRequest();
        console.log(response)
    } catch(error) {
        console.log(error)
    }
}
Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34