【问题标题】:Javascript - Storing Data from API call into Object [duplicate]Javascript - 将 API 调用中的数据存储到对象中[重复]
【发布时间】:2020-12-06 21:17:57
【问题描述】:

我正在尝试将来自 Novelcovid api 调用“api.countries({country:"USA"}).then(console.log)”的数据存储到 index_data 对象中。我正在使用函数 getData 将值存储到 index_data 对象中。我遇到的问题是 index_data 对象不会在 getData() 函数的范围之外更新,我希望能够全局访问分配给对象的新属性。任何关于我如何解决这个问题的想法都将不胜感激。


let totalConfirmed; 
                                          
let index_data = {
  totalConfirmedCases: null,
  totalConfirmedDeaths: null,
  totalRecovered: null,
  casesToday: null
};

api.countries({country:"USA"}).then(totalData);

function totalData(result) {
  totalConfirmed = result.cases; 
  getData(index_data, totalConfirmed);  
};

function getData(theObject, tcVar){
  theObject.totalConfirmedCases = tcVar;
}; 

console.log(index_data);

【问题讨论】:

  • "[...] index_data 对象不会在 getData() 函数的范围之外更新"–是的,但只有在您记录它之后价值。 “[...] 全局访问分配给对象的新属性”——您需要存储生成的 Promise 并使用 promise.then(index_data => /**/) 或使用 async/await

标签: javascript node.js function scope


【解决方案1】:

对象在 js 中(有效地)通过引用传递。问题不在于对象,而在于您登录到控制台时。由于您正在发出异步 api 请求,因此您应该在调用 getData 后进行控制台日志。

正如 str 在他的评论中建议的那样,您可以使用 async await 轻松完成此操作。

【讨论】:

    猜你喜欢
    • 2019-10-18
    • 2015-04-25
    • 2019-07-08
    • 1970-01-01
    • 2018-01-21
    • 2017-12-28
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多