How to return values from async functions using async-await from function?

Javascriptnode.jsAsynchronousAsync AwaitAxios

Javascript Problem Overview


How can I return the value from an async function? I tried to like this

const axios = require('axios');
async function getData() {
    const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
    return data;
}
console.log(getData());

it returns me this,

Promise { <pending> }

Javascript Solutions


Solution 1 - Javascript

You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e

async function getData() {
  return await axios.get('https://jsonplaceholder.typicode.com/posts');
}

(async () => {
  console.log(await getData())
})()

Working sample.

More information about async/await

Since axios returns a promise the async/await can be omitted for the getData function like so:

function getData() {
  return axios.get('https://jsonplaceholder.typicode.com/posts');
}

and then do same as we did before

(async () => {
   console.log(await getData())
})()

Solution 2 - Javascript

your function getData will return a Promise.

So you can either:

  • await the function as well to get the result. However, to be able to use await, you need to be in an async function, so you need to 'wrap' this:

    async function callAsync() {
       var x = await getData();
       console.log(x);
    }
    callAsync();
    

    (I named the function for sake of clarity, but in this scenario, one would rather use an anonymous function call; see TheReason's answer.)

or

  • use the result as a normal Promise, which is what an async function returns.
    You have to use then with a callback:

    getData().then(x => { 
        console.log(x); 
    });
    

Solution 3 - Javascript

The other answers have covered this fine; but I'd like to chip in and say get in the habit of creating and calling a main function rather than run things in the global scope. i.e.

async function main(){
  let result = await getData();
}

main().catch(console.log);

This is pretty clear to anyone reading your code that this is your app entry point

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKing RayhanView Question on Stackoverflow
Solution 1 - JavascriptThe ReasonView Answer on Stackoverflow
Solution 2 - JavascriptPac0View Answer on Stackoverflow
Solution 3 - JavascriptMeirion HughesView Answer on Stackoverflow