简体   繁体   English

如何存储从异步 function 返回的数据

[英]How can I store the data returned from an async function

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?有没有办法将从异步 function 返回的数据存储在 JavaScript 中?

I know, the async function will always return a promise, and can use ".then(func)" to do another thing with the data.我知道,异步 function 将始终返回 promise,并且可以使用“.then(func)”对数据做另一件事。 But how can i store it in a variable and use it later?但是我怎样才能将它存储在一个变量中并在以后使用呢?

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.如果您在getDetails()之前不使用await关键字,您将得到正确指出的 promise 而不是数据结果。

Note that await getDetails() only works when being called inside an async function.请注意, await getDetails()仅在async function 内部调用时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM