【发布时间】:2018-04-21 14:06:52
【问题描述】:
我在 Node.js 中有一行代码调用外部 API:
public.getInfo(console.log, config.data1);
并检索一些数据:
null { abc:
{field1: 0.234252,
{field2: 0.234252,
{field3: 0.234252,
{field4: 1,
{field5: 0.234252 },
{ xzy:
{field1: 0.234252,
{field2: 0.234252,
{field3: 0.234252,
{field4: 0.234252,
{field5: 0.234252 }}
我可以在控制台中看到结果。我有两个问题:
public.getInfo(console.log, config.data1);具有 console.log 作为“回调”功能。如果我不想打印这些数据,而只是在代码中的其他函数中使用它怎么办?如何“读取”API 响应?如何使用响应的 JSON 结构?例如:
abc -> fiels4 => 1
【问题讨论】:
-
只能通过回调函数获取数据。
-
删除
console.log并替换为你的回调函数function(err, data) { // data will be your response } -
太棒了!至少现在我对回调函数有了更好的理解;)我的新函数是:public.getInfo(function(err,data){}, config.data1);一旦我得到对象“数据”,我该如何浏览/投射/解析它?