如何在承诺、异步等待和映射操作符(如concatMap )之间作出决定?
这是我的具体案例,但我也很好奇你一般是如何决定的:
我正在给我的后端打一个http电话,然后再打另一个http电话。在处理来自第二个调用的json数据时,我需要使用第一个调用返回的值。在这种情况下,使用异步等待、承诺还是concatMap更好?此外,一般情况下,决定使用哪一种方法的指导方针是什么?
以下是我目前使用的concatMap。(我从getTask http调用动态生成子组件,每个子组件都需要访问annotationFormats)。
this.dashboardService.getAnnotationFormats()
.pipe(
concatMap(annotationFormats=> this.dashboardService.getTasks())
)
.subscribe(
(tasks)=>{
for(let task of tasks){
const componentFactory=this.CFR.resolveComponentFactory(DashboardItemComponent);
const componentRef=this.vc.createComponent(componentFactory);
componentRef.instance.task=task;
componentRef.instance.annotationFormats=annotationFormats;
componentRef.instance.compInteraction=this;
this.taskRef.push(componentRef);
}
}
);发布于 2019-11-12 22:03:08
异步/等待和承诺在不同的语法中基本相同。在某些作业完成后将运行一次的异步代码。
作为一种规则,我绝不会在使用角度的时候使用任何一个。“角”随RxJS而来,这比承诺要多得多。当作业完成后,您可以使用RxJS运行异步代码一次,但它也为您提供了创建数据流并以多种不同方式操作数据流的可能性。要完全理解RxJS和反应性编程确实需要一点时间,但一旦了解了,您就会意识到您可以用它做多少事情。
在您的例子中,我喜欢使用操作符forkJoin,因为这两个请求似乎相互独立。您可以给它一个您想要获得的资源列表,并在它们都完成后执行订阅中的异步代码,这使得它非常适合于http请求:
forkJoin({
annotationFormats: this.dashboardService.getAnnotationFormats(),
tasks: this.dashboardService.getTasks(),
})
.subscribe(
({tasks, annotationFormats})=>{
for(let task of tasks){
const componentFactory=this.CFR.resolveComponentFactory(DashboardItemComponent);
const componentRef=this.vc.createComponent(componentFactory);
componentRef.instance.task=task;
componentRef.instance.annotationFormats=annotationFormats;
componentRef.instance.compInteraction=this;
this.taskRef.push(componentRef);
}
}
);花点时间学习RxJS,我保证它会有回报的。每当您使用RxJS时,它感觉太复杂或错误,这是因为它可能是。直接进入RxJS文档,寻找一些可能有用的东西,如果你找不到任何东西,谷歌快速搜索可能会为你找到解决方案。重点是,不要只是盲目地使用它,永远试着理解它是如何工作的。
我希望这是有用的。:)
编辑:
对于RxJS < 6.5,语法有一点不同:
forkJoin(
this.dashboardService.getTasks(),
this.dashboardService.getAnnotationFormats()
)
.subscribe(
([tasks, annotationFormats])=>{
for(let task of tasks){
const componentFactory=this.CFR.resolveComponentFactory(DashboardItemComponent);
const componentRef=this.vc.createComponent(componentFactory);
componentRef.instance.task=task;
componentRef.instance.annotationFormats=annotationFormats;
componentRef.instance.compInteraction=this;
this.taskRef.push(componentRef);
}
}
);注意,我们将资源作为参数传递,而不是作为对象传递,订阅中的结果也将是数组形式,而不是对象。
发布于 2019-11-12 21:32:07
它们有不同的用途。当您想要在您编写了一些异步代码的地方停留时,可以使用异步/等待。而primises是用来发现执行异步代码和调用回调的地方的工具。
https://stackoverflow.com/questions/58826960
复制相似问题