这是在节点快速路由的上下文中。我收到带有ID列表的查询参数的get请求。现在,我需要为每个ID进行标注,并将标注的结果存储在数组或对象中。需要将第一个数组的每个元素(包含ID)映射到其相应的调用结果中。我没有办法修改从此路由访问的端点,因此我必须为每个ID进行一次呼叫。我已经进行了一些研究,到目前为止,我将代码和sudo代码混合在一起,如下所示:
const ids = req.query.ids;
const idMembers = Promise.all(ids.map(async id => {
// here I'd like to create a single object or associative array
[ id: await callout(id); ]
}));
当所有的诺言都解决了之后,我需要idMembers的最终结果是这样的:(响应将是一个带有嵌套数组和对象的对象,我在本文中只是对其进行了简化,但我需要从res.payload中获取它)
{
'211405': { name: 'name1', email: '[email protected]' },
'441120': { name: 'name2', email: '[email protected]' },
'105020': { name: 'name3', email: '[email protected]' }
}
哦,当然,我需要处理标注和promise失败,那是我对javascript缺乏经验成为一个真正的问题。感谢您的帮助!!
我有一些额外的想法,就是必须将已解决的承诺的结果映射到其id,然后在一个单独的迭代中,我可以创建最终的数组/对象,将ID映射到包含目的。但是,这仍然无法回答我的任何问题。我只是想提供我所收集和想到的尽可能多的信息。
Promise.all
返回结果数组(每个承诺一个项目)。
有了这种临时结构,便可以构建所需的对象。
const arrayOfMembers = Promise.all(ids.map(async id => {
// ...
return { id, value: await callout(id) } // short syntax for { id: id, value: ... } (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
}));
// arrayOfMembers = [
// { id: 211405, value: { name: 'name1', email: '[email protected]' } },
// ...
// ]
在纯JS中,可以使用for
循环或.forEach()
调用来完成:
const res = {};
arrayOfMembers.forEach(el => {
const { id, value } = el;
res[el] = value;
});
或使用一个reduce()
电话
const res = arrayOfMembers.reduce((accumulator, el) => {
const { id, value } = el;
return { ...accumulator, [id]: value };
}, {});
在两种情况下res
都是:
// res = {
// '211405': { name: 'name1', email: '[email protected]' },
// ...
// }
聚苯乙烯
有一个名为的便捷库lodash
。它具有大量用于数据处理的小方法。
例如,_.fromPairs()
可以[[key1, value1], [key2, value2]]
成对建立对象。
如您所述,您有lodash,所以我认为以下方法应该有效:
const arrayOfKeyValuePairs = Promise.all(ids.map(async id => {
// ...
return [ id, await callout(id) ] // array here so it matches what fromPairs needs
}));
const res = _.fromPairs(arrayOfKeyValuePairs);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句