Javascript 异步函数控制台记录返回的数据

标签 javascript json function asynchronous return

我如何控制日志 - 或者对从异步函数内部返回的数据做任何事情?

例子: JS 文件:

   async function getData(){
      try {
         $.getJSON('./data.json', (data) => {
            return data;
         });
      } catch(error) {
         console.log("error" + error);
      } finally {
         console.log('done');
      }
   }

   console.log(getData());

JSON 文件:

{
   "stuff": {
      "First": {
         "FirstA": {
            "year": [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         },
         "FirstB": {
            "year": [2007, 2008, 2009, 2010, 2011, 2012],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         }
      },
      "Second": {
         "SecondA": {
            "year": [2002, 2003, 2004, 2005, 2006],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         },
         "SecondB": {
            "year": [2007, 2008, 2009, 2010, 2011, 2012],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         }
      }
   }
}

如何返回/获取对 JSON 文件中所有信息的访问权并使用它。例如,我想将“First”和“Second”添加到一个 div 中。与“FirstA”和“FirstB”以及“SecondA”和“SecondB”...等相同。

就目前而言,我得到Promise {: undefined}

如有任何帮助,我们将不胜感激。

--------更新------------

如果我在函数内部运行控制台日志,那么我可以看到 json 数据,但我需要访问函数外部的数据。

谢尔盖

最佳答案

两个问题:

  1. 设置 async 函数创建的 promise 的解析值,您必须使用 return 语句async 函数本身。您的代码在 getJSON 回调(被忽略)中有一个 return,而不是 async 函数本身。

  2. 获取async 函数的解析值,您必须await 它(或以旧方式使用它的 promise ,通过 then 等)。

对于 #1,您可以返回 awaiting getJSON 的结果:

async function getData() {
    try {
        return await $.getJSON('./data.json').promise();
    }
    catch (error) {
        console.log("error" + error);
    }
    finally {
        console.log('done');
    }
}

对于 #2,您需要 await 您的函数(这又需要在 async 函数中):

console.log(await getData());

...或者通过 then 消费它的 promise :

getData().then(data => {
    console.log(data);
});

旁注:您的 getData 隐藏了错误,将它们转化为值为 undefined 的解决方案,这通常不是一个好主意。相反,确保它传播错误:

catch (error) {
    console.log("error" + error);
    throw error;
}

然后,自然而然地,确保任何使用 getData 的东西都处理或传播错误,确保某个地方确实处理了它(否则,你会得到一个“未处理的拒绝”错误)。


回复你的评论

how would I access the "stuff" in the json file from the log outside the function?

getData的异步结果/解析值是JSON定义的对象(已经不是JSON了,已经解析过了)。所以你会在上面使用 .stuff,例如:

// In an `async` function
console.log((await getData()).stuff);

// Or using `then`:
getData().then(data => {
    console.log(data.stuff);
});

关于Javascript 异步函数控制台记录返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48036038/

相关文章:

当 () 包含在调用中时,JavaScript 递归函数中断

java - 当参数中已提供字节数组对象时,为什么某些 Java 函数需要字节数组长度?

javascript - es6 如何在 if 语句中使用 console.log ?

javascript - WebSocket 连接失败。 Websocket 握手期间出错。响应代码 403?

javascript - 根据 json 数组的键创建 jQuery 数组

javascript - 如何在这个基于正则表达式的 JSON 到 XML 转换器中处理嵌套数组

javascript - JS如何返回所有同姓的人

javascript - 扩展 Node.js 中模块的功能

python - 如何从 Azure Data Lake Store 读取 Azure Databricks 中的 JSON 文件

javascript - 调用 Function.prototype.method() 时 TypeError : this. prototype is undefined