本文介绍了如何通过RxJ合并或分组到Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法返回结果,如下所示:

I have the following method that returns result as shown below:

result: [ { status: 200, ... }, { status: 200, ... }, { status: 400, ... }, ... ]
    

我需要使用状态值对结果进行分组,并且仅返回2个结果,而不是上面示例结果中的3个:

I need to group the result by using status value and return only 2 results instead of 3 for the example result above:

update() {
  this.demoService.update(...).toPromise()
  .then(result => {

    const message = result.map((x: any) => {
      if (x.status === 200) {
        return {
          text: 'successful'
        };
      } else {
        return {
          text: 'fail'
        };
      }
    });

    }
  })
}

我尝试使用RxJs的 groupBy ,但是我认为Promise不能使用它.那么,如何在上面的示例中将此结果分组?

I tried to use groupBy of RxJs but I think it cannot be used in Promise. So, how can I group this result in the example above?

推荐答案

我不确定它是否有效,但是您可以尝试(您仅过滤状态不同的实体,然后仅选择状态):

I'm not sure it works, but you can try (you filter only entities with distinct status, then select only statuses):

update() {
  this.demoService.update(...).subscribe(result => {
    const messages = result
        .filter((x, i, arr) => arr.findIndex(t => t.status === x.status) === i)
        .map(x => x.status);

    // do stuff
  });
}

这篇关于如何通过RxJ合并或分组到Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 07:44