0

A have a code for a simple api request, that should yield some data and it does! But it returns this data only in .then() block. Any attempt to save it in a variable lends in undefined. Where did I go wrong?

const link = "https://semalt.net/dev/api/v1/example/test/";
let queryData;
async function getData(link) {
  try {
    const result = await fetch(link);
    const data = await result.json();
    return data.result;
  } catch {
    alert(error);
  }
}
getData(link).then((array) => {
  queryData = array;
  console.log(queryData);
});
Not-a-Whale
  • 99
  • 2
  • 8
  • 2
    It stays `undefined` until the `then` callback actually runs. Don't access it before that happened. – Bergi Apr 26 '20 at 19:33
  • This is how async function is supposed to work. https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron has really good examples regarding 'asynchronous flow'. – bgmn Apr 26 '20 at 19:35
  • But I try to access it after! For example: getData(link).then((array) => { queryData = array; console.log(queryData); }); console.log(queryData) // STILL UNDEFINED! – Not-a-Whale Apr 26 '20 at 19:37
  • Like when I try to get the value after then() i still get undefined! Help me)) – Not-a-Whale Apr 26 '20 at 19:44
  • @Not-a-Whale I said *after* the (asynchronous!) callback *runs*. Not *below* the `then()` call. – Bergi Apr 26 '20 at 19:48
  • But like how? I don't get it. Inside of the .then() block? – Not-a-Whale Apr 26 '20 at 19:50

0 Answers0