0

Why does this function not wait for the promise to be answered? How would a correct application of the async / await principles be?

My Code

var axios = require('axios');
var data = JSON.stringify({});


const getClient = async function () {
  
  var config = {
    method: 'get',
    url: `https://reqbin.com/echo/get/json`,
    headers: { 
    },
    data : data
  }

  const res = await axios(config)
  .then(function (response) {
    console.log(response.data)
  })
  .catch(function (error) {
    console.log(error);
  })
  return res
}
console.log(getClient())

TERMINAL

Promise { <pending> }
{ success: 'true' }
  • `console.log(getClient().then(response => console.log(response))` – rags2riches-prog Dec 09 '20 at 17:06
  • Full explanation here: [Fetch api always returning promise](https://stackoverflow.com/questions/65165098/fetch-api-always-returning-a-promise/65165320#65165320) as all `async` functions always return a promise. – jfriend00 Dec 09 '20 at 17:16

2 Answers2

2

Why does this function not wait for the promise to be answered?

Because you aren't awaiting it.

How would a correct application of the async / await principles be?

console.log(await getClient())

NB: Requires an environment with top-level await or being moved into an async function. You could use getClient().then(value => console.log(value)) instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

async is by itself a promise, so it's execution always resolves a promise.

You can handle it like a promise (if you read the article you will learn a lot about how async programming works in javascript), so you have 2 options:

Or when you run this function inside another async/await function, use the keyword await

async run () { 
 console.log(await getClient())
} 
run()

Or using the word then like for axios.

getClient().then((client) => console.log(client))
SirPeople
  • 4,248
  • 26
  • 46