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

King Rayhan picture King Rayhan · Apr 20, 2018 · Viewed 74.6k times · Source

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> }

Answer

The Reason picture The Reason · Apr 20, 2018

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())
})()

Worked 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())
})()