Javascript异步功能控制台记录返回的数据 [英] Javascript async function console log the returned data

查看:187
本文介绍了Javascript异步功能控制台记录返回的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I console log - or do any thing with the data returned from inside an async function?

示例: 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" ...相同.

How can I return / get access to all the information in the JSON file and work with it. for example I'd like to take the "First" and "Second" and add them to a div. Same with "FirstA" and "FirstB" and "SecondA" and "SecondB"...and so on.

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

Right now as it stands, I get Promise {: undefined}

任何帮助将不胜感激.

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

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

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

If I run the console log inside the function I then can see the json data, but I need access to the data outside the function.

同步

推荐答案

两个问题:

  1. 设置async函数创建的promise的分辨率值,必须使用来自async函数本身的return语句.您的代码在getJSON回调中具有return(将被忽略),而不是async函数本身.

  1. To set the resolution value of the promise created by the async function, you have to use a return statement from the async function itself. Your code has a return in the getJSON callback (which is ignored), not the async function itself.

获取功能的分辨率值,您必须await(或通过then以更旧的方式使用它的promise,等等).

To get the resolution value of an async function, you must await it (or consume its promise in the older way, via then, etc.).

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

For #1, you could return the result of 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函数内部):

And for #2, you'd need to either await your function (this would, in turn, need to be inside an asyncfunction):

console.log(await getData());

...或通过then兑现承诺:

...or consume its promise via then:

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


旁注:您的getData隐藏错误,将其转换为值为undefined的分辨率,通常这不是一个好主意.相反,请确保它传播错误:


Side note: Your getData hides errors, turning them into resolutions with the value undefined, which is generally not a good idea. Instead, ensure that it propagates the error:

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

然后自然地确保使用getData的任何东西都可以处理或传播该错误,并确保在 某个地方可以处理该错误(否则,您将收到未处理的拒绝"错误).

Then, naturally, ensure that anything using getData either handles or propagates the error, making sure something somewhere does handle it (otherwise, you get an "unhandled rejection" error).

发表您的评论

如何从函数外部的日志中访问json文件中的内容"?

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

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

The async result / resolution value of getData is the object the JSON defined (it's no longer JSON, it's been parsed). So you'd use .stuff on it, e.g.:

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

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

这篇关于Javascript异步功能控制台记录返回的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆