0
async function getDetails(country){
  let response = await fetch(`https://restcountries.com/v2/name/${country}`);
  let [data]= await response.json();
  return data
}

let portugal = getDetails('portugal');

Is there a way to store the data returned from a async function in JavaScript?

I know, the async function will always return a promise, and can use ".then(func)" to do another thing with the data. But how can i store it in a variable and use it later?

Dan
  • 61,568
  • 9
  • 61
  • 78
Afam Rk
  • 19
  • 4
  • 3
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Lawrence Cherone Mar 27 '22 at 15:16

1 Answers1

6

Yes you can.

let portugal = await getDetails('portugal');

If you don't use await keyword before getDetails() you will get the promise as you correctly pointed out and not the data result.

Note that await getDetails() only works when being called inside an async function.

kvooak
  • 275
  • 1
  • 3
  • 9
  • You can use [.then](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) too (Without await infront of course) – Rooki Mar 28 '22 at 13:07