【问题标题】:How to make asynchronous calls parallel without stalling the queued calls如何在不停止排队调用的情况下使异步调用并行
【发布时间】:2020-06-18 10:45:29
【问题描述】:

我有 50 个科目,我发送 50 个并行调用,每个科目返回 1 个或多个学生数据 例如:如果我发送一个 subjectId,this.subjectService.getStudentsData(subjectId) 它返回学生数据:

[
{StudentId:1,
"FirstName":'firstName', 
"ListOfSubjects":[{Subjectid:1,SubjectName:'Maths', .....somedata:[{1:a,2:b...}, {3:y,2:x...}]}},

{
StudentId:2, 
FirstName:secondName, 
.
.
ListOfSubjects:[
{Subjectid:1,SubjectName:'Maths', .....somedata:[{c:1,d:2...}, {a:y,b:x...}]}}]

现在我需要在通过用户数据获取用户时进行绑定,但完成所有服务调用需要 15 分钟

我用的是

const requests: any = subjectIds.map(id => {   
            const t: any = {...data};
            t.SubjectId = [id];
          return this.studentService.getStudentsData(t);
        });

【问题讨论】:

  • 如果您只使用地图,请求将在后续发送。如果您想并行发送它们,请使用 forkJoin 方法:learnrxjs.io/learn-rxjs/operators/combination/forkjoin
  • 我需要绑定到 UI,因为我得到每个请求的响应并将下一个响应添加到原始响应等等,所以我认为 forkjoin 在这里没有帮助

标签: angular asynchronous


【解决方案1】:

就像mamichels 说你可以使用forkJoin,但我记得读过forkJoin 最多只能做6 个,除非你可以使用dictionary

我愿意:

const requests: any = combineLatest(...subjectIds.map(id => this.studentService.getStudentData(id) /* you know what should go in the argument */)
...
requests.subscribe(responseArray => console.log(responseArray));

==========================编辑==================== =====

要获得每个请求完成的通知,我会使用merge

import { merge } from 'rxjs';

const requests: any = merge(...subjectIds.map(id => this.studentService.getStudentData(id));

....
requests.subscribe(response => { /* handle each response as it returns */ }));

================= 好吧,试试老派的方法================

for (let i = 0; i < subjectIds.length; i++) {
  this.studentService.getStudentsData(subjectIds[i].StudentId/* again, I am not sure what goes here as argument */).subscribe(
  response => {
    console.log(response);
  }
);
}

【讨论】:

  • 我需要每个响应,以便我可以将每个响应绑定到 UI 等等
  • 如果有 10 个调用很少会并行,而其他调用则停滞不前,直到其他调用完成,不确定是什么问题
  • 我认为这些是 HTTP 1 和 HTTP 2 的限制。不过我不确定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多