7

I need to fetch some JSON data from an API and assign the result to a variable. I can see the array of data in the console, but [abc] is always set as a Pending promise.

I've tried to assign [abc] instead of logging [data] or simply returning [data] but it's not working. Ideally, I would also want to stop the execution of the following code until I get the required data but with the code I have, the text gets logged before the data

async function fetchData() 
{
  let response = await fetch('API');
  let data = await response.json();
  data = JSON.stringify(data);
  data = JSON.parse(data);
  return data;
}

let abc = await fetchData()
  .then(data => console.log(data)); 

console.log('This should not be logged if 'abc' does not have the data i need')

(data => console.log(data)) ..>> here the data is the array I need but I have no idea on how to assign on a variable.

I've looked for many solutions on the internet but I couldn't find anything that could help.

EDIT 1:

If I assign: let abc = await fetchData() without the then statement it throws me this error: Uncaught SyntaxError: await is only valid in async function

If I then remove the await keyword it returns Promise without having it resolved.

John
  • 151
  • 1
  • 1
  • 8

2 Answers2

10

In order for await keyword to work, it must sit inside a async function. So you need to wrap your code in a async function first, let's say a main function, then call it. Example:

async function fetchData() {...}

async function main() {
  let abc = await fetchData();
  console.log(abc);
}

main();
hackape
  • 18,643
  • 2
  • 29
  • 57
  • Thanks for clarifying, I eventually got to that solution and I can see many uses a IIFE. Yet I am still confused on how to reference that values (abc) externally to let my application work. I mean, even after main() has resolved, I can access [abc] inside the function but not outside and it does not let me assign an external variable to it – John Apr 09 '19 at 15:41
  • No, no obvious solution to do that. Unless you also move that "external" code into that main function. You don't get to pass that variable externally for free. – hackape Apr 09 '19 at 15:48
  • @Peter You need to understand the fundamental difference btw sync/async code. The `async/await` is merely syntax sugar, it doesn't magically turn what is fundamental impossible possible. – hackape Apr 09 '19 at 15:49
  • That's actually what I am looking to do. I need to fetch some data and work with them on the whole application, not only inside a separate function. I am writing the app in plain JS at first and I am stuck doing this. I know in React I can save the data in store and it would be easier. – John Apr 09 '19 at 15:51
  • @Peter also did you accidentally down vote the other answer? If I misunderstand I shall apologize, but if it's you, that's not nice. – hackape Apr 09 '19 at 15:52
  • @Peter Yeah, you get the idea. Like with `store`, you need some kind of pub/sub mechanism to orchestrate sync/async code. That doesn't come for free, need to implement such thing. – hackape Apr 09 '19 at 15:56
  • All right. So what I am trying to do is actually not possible on plain JS and I need to rely on something else. Also regarding the downvote, it was not me as I am a new member and my votes are not displayed. Glad it got removed cause it actually helped me realize I missed to describe that scenario in the post as you can see in the comments – John Apr 09 '19 at 15:58
  • @Peter yep. Make sure to read this [answer](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). And perhaps upvote/accept mine would be nice :D – hackape Apr 09 '19 at 16:03
5

it should be like this

async function fetchData(){
 let response = await fetch('API');
 let data = await response.json();
 data = JSON.stringify(data);
 data = JSON.parse(data);
 return data;
}

let abc = await fetchData(); // here the data will be return.
console.log(abc); // you are using async await then no need of .then().
Amit Chauhan
  • 1,810
  • 3
  • 17
  • 25