【问题标题】:How to wait for all stream results and return final result as object? [closed]如何等待所有流结果并将最终结果作为对象返回? [关闭]
【发布时间】:2019-12-18 18:37:21
【问题描述】:

我是 rxjs 的新手,这是我最近遇到的一个简单问题。我正在尝试使用 Promise 实用程序循环数组。我的期望是等待所有流结果和流结束并将其作为对象返回。但是,我不确定如何组合所有流并将它们作为单个对象返回。

我已经尝试过toArray(),我认为这是我想要的最接近的答案,但我希望会有一些类似于toArray() 的运算符,比如toObject()。我知道有一个运营商叫forkJoin(),但我不确定在我的情况下如何使用它。

这是我的代码

const textList = [
  {
    key: "text1key",
    label: "text1"
  },
  {
    key: "text2key",
    label: "text2"
  },
  {
    key: "text3key",
    label: "text3"
  }
];

const myPromise = (data) => new Promise((resolve, reject) => {
  resolve("translated" + data);
})

const source = from(textList).pipe(
  concatMap(textObj =>
    myPromise(textObj.label).then(result => ({ key: textObj.key, value: result }))),
  map(({ key, value }) => ({ [key]: value })),
  toArray(),  // expect to return a single object instead of array.
);

source.subscribe(finalResult => console.log("FINAL RESULT", finalResult));

期望在订阅期间获取对象而不是数组。

【问题讨论】:

  • 可能你需要使用reduce而不是map
  • ArtemArkhipov 是的,你说得对,我不知道,谢谢

标签: angular typescript rxjs


【解决方案1】:

您需要使用reduce 而不是maptoArray。因此导入reduce 运算符并将代码更改为以下内容:

const textList = [
  {
    key: "text1key",
    label: "text1"
  },
  {
    key: "text2key",
    label: "text2"
  },
  {
    key: "text3key",
    label: "text3"
  }
];

const myPromise = (data) => new Promise((resolve, reject) => {
  resolve("translated" + data);
})

const source = from(textList).pipe(
  concatMap(textObj =>
    myPromise(textObj.label).then(result => ({ key: textObj.key, value: result }))),
  reduce((acc, {key, value}) => {
    acc[key] = value; // add key and value into accum
    return acc;  // return accum for the next iteration
  }, {}) // set an initial value (accum) as empty object
);

source.subscribe(finalResult => console.log("FINAL RESULT", finalResult)); // { translatedtext1Key: text1, ... }

Reduce 采用回调函数,其中累积值是第一个参数,数组项作为第二个参数。它与reduce 处理简单数组的方式非常相似。 你可以阅读更多关于它的信息here

【讨论】:

  • 谢谢,这正是我想要的。我没有注意到 rxjs 运算符中有一个reduce
猜你喜欢
  • 1970-01-01
  • 2023-01-26
  • 2019-06-22
  • 2021-05-09
  • 2021-07-22
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多