代码之家  ›  专栏  ›  技术社区  ›  aghosh03 Prateek Thapa

如何从异步获取函数中提取数据

  •  0
  • aghosh03 Prateek Thapa  · 技术社区  · 3 年前

    这看起来应该非常简单和基本,但我无法从异步获取函数中获取数据。下面是我的代码。我们非常感谢您能深入了解我可能做错了什么。

    const getData = async(url)=>{
        try{
          const response = await fetch(url);
          const data = await response.json();
          console.log(data) //<-- this is working
          return data;
        }
        catch (error){
          console.log(error);
        }
    }
    
    const desiredData = getData(url);
    console.log(desiredData) // <--this is empty
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Stosian    3 年前

    调用异步函数会返回一个Promise对象。您可以尝试这样做:

    const desiredData = getData(url);
    desiredData.then((value) => console.log(value))
    

    你也可以检查一下 link