javascript - 使用项目计数创建新对象
问题描述
我想创建一个从少数来源获取参数的函数,并返回一个带有新对象的承诺。所以,我有一个包含所有数据的基础对象,还有另一个函数,它接受一个参数并进行一些操作并返回另一个数据。主要问题是我有一些竞争条件或新对象没有按需要更改,可能是因为嵌套函数。
我试图查看其他答案,但没有成功。
足够的介绍,这是我的一些代码:
imports...
const createNewObject = async () => {
try {
const baseObjFromRequest = await myClient.request(query); // Returns array of objects
// this is the base object structure that returns from request:
baseObjFromRequest = [
{data: "some data x", val: 1},
{data: "some data y", val: 8},
{data: "some data z", val: 7},
{data: "some data x", val: 3},
{data: "some data z", val: 11},
]
// the pipeline should iterate over the array, with the converter function
// and return the info as the key of the new object
// which key is a counter of the values
newObject = {}
baseObjFromRequestAbove.forEach(item => {
let keyFromConverter = converter(item.data);
newObject[keyFromConverter] += item.val;
})
// Now I want to return new object (as promise)
// in this structure, but somehow it breaks any time and not return it as well.
newObject = {
info_from_x: 4, // The value is the count of
info_from_y: 8,
info_from_z: 18,
}
return newObject; // As promise
} catch (error) {
console.error(err);
}
}
// This function do a call and convert the data to new info data
const converter = async (data) => {
let query = { "info": data }
try {
const resp = await axios.post(URL + '/info', query);
const data = await resp.data;
return data;
} catch (err) {
console.error(err);
}
};
解决方案
推荐阅读
- json - 使用 Map 绑定复选框(true、false)
- git - 在 AWS Amplify Build 中获取私有子模块
- powershell - 如何使用 Form resize 调整表单控件的大小
- fortran - 不同指针类型的通用接口
- c# - 未找到 NetCore 3.0.0 框架版本,即使它已安装在 MacOS 中
- java - Hazelcast Delta 更新
- xaml - 如何使用 Xbox 控制器在 ListView 中的多个 GridView 之间导航项目?
- android - SQLite:Android中的“没有这样的表”
- node.js - 在 VS Code 中调试 webpack.mix.js - 未验证的断点
- reactjs - 如何在 Reactjs 中实现服务器端渲染