简体   繁体   English

如何聚合 javascript 中 2 个 Promise 返回的数据

[英]How to aggregate data returned by 2 Promises in javascript

I have 2 promises being imported in a js file.我在 js 文件中导入了 2 个承诺。 employees, managers Both these promises contains data as Array of Json objects.员工、经理 这两个承诺都包含 Json 对象数组形式的数据。 eg例如

employees = [ {"id": 1, "name": "Andrew", "age": 22}, {"id": 2, "name": "Eric", "age": 34}] 
managers = [ {"id": 1, "name": "Andrew", "department": "logistics"}, {"id": 2, "name": "Eric", "department": "sales"}]

I want to merge these data sets based on id and return single array of Json objects like below-我想基于 id 合并这些数据集并返回 Json 对象的单个数组,如下所示 -

empManager = [ {"id": 1, "name": "Andrew", "age" : 22, "department": "logistics"}, {"id": 2, "name": "Eric", "age": 34, "department": "sales"}]

I am trying something like below using Promise chaining but it is not working我正在尝试使用 Promise 链接,但它不起作用

import {employees, managers} from './model';

export let empManager = function getData() {
    let employees;
    employees().then(emps => {
        employees = emps;
        return managers;
    }).then(mgrs => {
        return employees.map( e=> Object.assign(e, mgrs.find(m => m.id == e.id)))
    })
}

Further when I am trying to fetch the value from empManager as below, it is giving error.此外,当我尝试从 empManager 获取值时,如下所示,它给出了错误。

console.log(empManager())  // error - "mgrs.find is not a function".

How should I achieve this aggregation on result from 2 promises?我应该如何根据 2 个承诺的结果实现这种聚合?

You could first resolve both promises using Promise.all .您可以首先使用Promise.all解决这两个承诺。

// Mimic async call.
employees = () => new Promise(resolve => resolve([ {"id": 1, "name": "Andrew", "age": 22}, {"id": 2, "name": "Eric", "age": 34}]));
managers = () => new Promise(resolve => resolve([ {"id": 1, "name": "Andrew", "department": "logistics"}, {"id": 2, "name": "Eric", "department": "sales"}]));

// Wrap in async anonymous function to be able to use await.
(async () => {

  // Use Promise.all to wait for both calls
  const [emps, mgrs] = await Promise.all([
    employees(),
    managers()
  ]);

  // Merge epmloyees
  const merged = {};
  emps
    .concat(mgrs)
    .forEach(u => {
      if(!(u.id in merged)) {
        merged[u.id] = {};
      }
      for(const key in u) {
        merged[u.id][key] = u[key];
      }
    })
  ;

  // Convert merged object into array again.
  console.log(Object.values(merged));

})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM