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

问题描述 投票:1回答:1

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

示例:JS FILE:

   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}

任何帮助将不胜感激。

--------- --------- UPDATE

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

哔叽

javascript json function asynchronous return
1个回答
3
投票

两个问题:

  1. 要设置async函数创建的promise的分辨率值,必须使用return函数本身的async语句。你的代码在return回调中有一个getJSON(被忽略),而不是async函数本身。
  2. 要获得async函数的分辨率值,您必须await它(或以旧方式,通过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你的函数(反过来,这需要在asyncfunction内):

console.log(await getData());

...或通过then消费其承诺:

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

旁注:你的getData隐藏了错误,将它们变成了值为undefined的分辨率,这通常不是一个好主意。相反,请确保它传播错误:

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

然后,自然地,确保使用getData处理或传播错误的任何事情,确保某处某处处理它(否则,您会得到“未处理的拒绝”错误)。


你的评论

如何从函数外部的日志中访问json文件中的“stuff”?

getData的异步结果/分辨率值是JSON定义的对象(它不再是JSON,它已被解析)。所以你在它上面使用.stuff,例如:

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

// Or using `then`:
getData().then(data => {
    console.log(data.stuff);
});
© www.soinside.com 2019 - 2024. All rights reserved.