javascript - 运行reduce,map函数
问题描述
我在 country.json 中有 3 个类和数据
国家.json
[{"country":"Algeria","region":"Northern Africa","code":"DZ","population":41318142,"cities":["Boumerdas","Zeribet el Oued","Zeralda"]},{"country":"American Samoa","region":"Polynesia","code":"AS","population":55641,"cities":["Aūa","Vaitogi","Vailoatai"]}
在 countryRep 类中,我使用这个函数来获取人口总和
async getSumAllPopulation(){
let countries = await this.getCountries();
let populations= countries.map(s=>s.population).reduce((acc, s) => s + acc);
return populations;
}
在测试中我写
app.get('/PopulationSum', async (req, res) => {
const countries = await repo.getSumAllPopulation();
res.send(countries);
})
getCountries() 函数
async getCountries() {
try {
const countries = await fs.readJSON(this.countryFilePath);
return countries;
}
catch (e) {
console.log(e)
}
}
但是我没有得到 sum 的结果?我该如何解决?我收到一个错误,似乎该方法没有返回任何东西。
解决方案
推荐阅读
- ruby-on-rails - PG::UndefinedColumn: 错误: 列 services.zip_code 不存在
- c - fscanf - 如何知道 EOF 是否意味着文件结束或读取/另一个错误?
- javascript - 使用 NpmPrettyMuch 的 Karma-Webpack 接线问题
- javascript - React Native-更新数组中对象的属性
- javascript - 如何关联 fullcalendar 中的资源和事件以在数据库中一起更新?
- django - django makemigrations 无法识别新模型
- android - 将图像上传到服务器android时出现空点异常
- azure-devops - 将标签推送到外部 git 不会触发 Azure Pipelines CI
- cucumber - 有没有办法将枚举列表传递给黄瓜 4.x 和 java
- javascript - 将 Angular v8 升级到 Angular v9 获取“ngx-mat-select-search”对“@angular/material”有不兼容的对等依赖