0

I have a function

function getData(foo) {
 return axios.get(url+foo)
  .then(response => response.baz)
  .catch(error => console.log(error))
}

Somewhere else in my code I call it.

function baz() {
  //....
  document.getElementById('bar').textContent = getData()
 //....
}

But then I end up with the text of [object Promise] inside my element.

Why does this happen and how can I make sure only the true value gets inserted without using async/await?

ProEvilz
  • 5,310
  • 9
  • 44
  • 74
  • "*Why does this happen*" - because you are returning a promise from `getData()`. "*how can I make sure only the true value gets inserted?*" - by using `.then(…)` with a callback if you don't want to use `async`/`await`. You cannot access the value from the future immediately. – Bergi Nov 14 '18 at 22:12

1 Answers1

2

Your getData() function returns a promise. So you would need to either use await or use .then chain when calling getData(). I suggest you use await if you can. Make sure to declare you baz as async if you do:

async function baz() {
  //....
  document.getElementById('bar').textContent = await getData();
 //....
}

If you don't want to use await, call then like so:

function baz() {
  //....
  getData().then(data => {
     document.getElementById('bar').textContent = data;
  }

 //....
}
Kon
  • 4,023
  • 4
  • 24
  • 38
  • so then am I right in assuming I won't need the `then()` in the `getData()` function? It seems somewhat obsolete if I just use `then()` as you suggested – ProEvilz Nov 14 '18 at 22:22
  • I mean, if I use `then()` like `getData().then()`, do I still need the `then()` inside `baz()` ? – ProEvilz Nov 14 '18 at 22:35
  • Correct, would need to make sure that data transformation is handled in getData().then(). – Kon Nov 14 '18 at 22:39