javascript - Angular make multiple http request but wait for each one to finish before making a new one - Stack Overflow

In angular app I have an array of literal objects containing a url property.I need to make a http requ

In angular app I have an array of literal objects containing a url property. I need to make a http request for each of these object, but one after another.

example:

let arr = [
    {url: ''},
    {url: ''},
    {url: ''}
]

(that is an example, they may be more of objects, and I don't know how many)

Now, I want to make a request to first url and when we have a response from it (or error, doesn't matter) THEN I want to make a request to second etc. Any idea how to efficiently implement that?

I don't want to make these request at single time - each one should be made only after previous was successful or failure.

In angular app I have an array of literal objects containing a url property. I need to make a http request for each of these object, but one after another.

example:

let arr = [
    {url: 'http://example./url1'},
    {url: 'http://example./url2'},
    {url: 'http://example./url3'}
]

(that is an example, they may be more of objects, and I don't know how many)

Now, I want to make a request to first url and when we have a response from it (or error, doesn't matter) THEN I want to make a request to second etc. Any idea how to efficiently implement that?

I don't want to make these request at single time - each one should be made only after previous was successful or failure.

Share Improve this question edited Jul 25, 2021 at 6:46 Aviad P. 32.7k15 gold badges111 silver badges126 bronze badges asked Dec 12, 2018 at 7:27 deasedease 3,07613 gold badges42 silver badges77 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 1

A possible solution would be to use concatMap, toArray and switchMapTo.

So first you have a list of urls:

let arr = [{url: 'http://example./url1'},{url: 'http://example./url2'}]

Then you transform them to an Observable:

of(arr)
.pipe(
   concatMap(r=> http.get(r.url)), //MAKE EACH REQUEST AND WAIT FOR COMPLETION
   toArray(), // COMBINE THEM TO ONE ARRAY
   switchMapTo(http.get("FINALURL") // MAKE REQUEST AFTER EVERY THING IS FINISHED
)).subscribe()

We can use tricky method for this. You have to create method in the service like below.

// TestService.ts
callUrlAsync(url): any[] {
    return this._http.get<any>(url);
  }

In the ponent you have to call this method as follows.

//ponent.ts

let arr = [{url: 'http://example./url1'},{url: 'http://example./url2'}, 
{url:'http://example./url3'}]

public i = 0;

//trigger method
testMethod(){
this.callUrl(this.arr[0]);
}

callUrl(url){
this.testService.callUrlAsync(url)
  .subscribe(data => {
    console.log(data);
      if(this.arr.length > this.i){
      this.i++;
      this.callUrl(this.arr[this.i]);
}
  }
  }, error => {
    this.Error(error);
    if(this.arr.length > this.i){
    this.i++;
    this.callUrl(this.arr[this.i]);
}
  }
  );
}

You can bine your observables with flatMap. Since you have a list of observables (or a list of urls that you want to transform into observables), you can do this with reduce.

Example:

// just some options to make a simple GET without parsing JSON
// and reading the response status
const httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Content-Type': 'application/x-www-form-urlencoded'
  }),
  responseType: 'text',
  observe: 'response'
}; 

const urls = [
  { url: 'www.google.' },
  { url: 'www.stackoverflow.' },
  { url: 'www.imgur.' },
  { url: 'www.reddit.' },
];

const reducer = (cur, acc) => acc.pipe(
  flatMap(r => cur)
);

const all$ = urls.map(({url}) => 
                    // create the get requests
                    http.get(url, httpOptions).pipe(
                      // do something with the result
                      tap(r => console.log(r.url + ': ' + r.status))
                 ))
                 .reverse()
                 .reduce(reducer);

all$.subscribe(x => {});

User forkJoin Fork Join

let arr = [{url: 'http://example./url1'},{url: 'http://example./url2'},{url: 

'http://example./url3'}]

forkJoin(arr);

Use concatAll() method from rxJs which collect observables and subscribe to next when previous pletes. (Or you can use forkJoin for multiple request at single time.)

forkJoin - This will group all your request and execute one by one. forkJoin waits for each http request to plete and group’s all the observables returned by each http call into a single observable array and finally return that observable array.

It accepts array as parameter. for example -

    let response1 = this.http.get(requestUrl1);
    let response2 = this.http.get(requestUrl2);
    let response3 = this.http.get(requestUrl3);
    return Observable.forkJoin([response1, response2, response3]);

For ref. - https://medium./@swarnakishore/performing-multiple-http-requests-in-angular-4-5-with-forkjoin-74f3ac166d61

This operator is best used when you have a group of observables and only care about the final emitted value of each.

In another way you can call each request in previous request's error or success block, which is lengthy process.

Use concatMap, make sure to catchError because you don't want the entire chain to fail if one link produced an error.

StackBlitz

let results$ = from(arr).pipe(
  concatMap(({ url }) =>
    requestData(url).pipe(catchError(err => of(`error from ${url}`)))
  )
);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745620538a4636490.html

相关推荐

  • 精品网络时代:联通AS9929与10099的强强联合

    中国联通的网络架构犹如一座精心设计的立交桥系统,由AS4837、AS9929和AS10099三张骨干网共同构建。这三张网络各司其职又相互配合,形成了联通独具特色的网络服务体系。联通AS4837、AS9929和AS10099线路介绍一、线路组

    1小时前
    20
  • 如何使用python查询Prometheus监控数据

    一.环境准备软件库包版本python3.8prometheus-api-client0.5.7二.安装步骤代码语言:python代码运行次数:0运行复制pip3 install prometheus-api-client默认安装最新版本的p

    1小时前
    20
  • 怎么用html写出哆啦A梦?

    用HTML和CSS来画哆啦A梦(Doraemon)是一项有趣且具有挑战性的任务。虽然HTML和CSS主要用于网页布局和样式,但通过巧妙的组合和定位,可以创建出相对简单的图形和图案。下面是一个简单的示例,展示了如何用HTML和CSS绘制哆啦A

    1小时前
    00
  • 流固耦合:基本概念、适用软件及 Abaqus 与 Powerflow 的协同仿真

    在工程和科学研究的诸多领域,流固耦合现象广泛存在且对系统性能有着关键影响。理解流固耦合的本质及其应用,对于优化设计、保障安全运行意义重大。同时,借助专业的流固耦合软件,能够更高效地对相关问题进行分析与模拟。接下来,让我们深入探究流固耦合的奥

    1小时前
    00
  • 文章降 AI 痕迹方法与工具速览

    文章降AI的方法和工具汇总‌如下: 这几天又认真研究类了一下,想让 AI 生成的文章更自然,摆脱程式化痕迹,可尝试以下方法。借助 GPT、文字滚筒鸭,朱雀大模型检测器、豆包、kimi 等大模型,输入文本后,它们能通过调整结构、替换同义词等操

    1小时前
    00
  • MySQL 8.4 配置SSL组复制(八个步骤)

    环境这里有三台MySQL主机,分别是192.168.3.71,72,73,主机名分别对应71.3_mgr1,72.3_mgr2,73.3_mgr3,操作系统均为Oracle Linux 8.10 X64,MySQL版本均为MySQL 8.4

    1小时前
    00
  • MySQL 8.4 配置复制

    参考文档:.4enreplication-configuration.html1.先在源数据库主机的myf添加这几项代码语言:javascript代码运行次数:0运行复制[mysqld]server-id = 2binlog_forma

    1小时前
    00
  • 用安信可Ai

    以下作品由安信可社区用户业余菜狗制作前言自从接触智能家居之后,笔者就变得很依赖智能家居(绝对不是懒!)比如卧室灯,就在进门的地方,进门开灯很方便,但是晚上睡觉关灯就很不方便。之前是买了一款Wi-Fi灯,是用手机APP操作,刚开始用的时候感觉

    1小时前
    00
  • AI生态暗战升级,科技巨头铁幕下的终极博弈

    一场围绕AI与智能体的标准、协议及生态的暗战已然蓄势待发。在美剧《权力的游戏》中,不到终局,主角归属始终成谜。如今的AI行业,正上演着同样扣人心弦的戏码。这并非是传统意义上的军事或政治博弈,而是一场围绕AI与智能体的标准、协议及生态展开的暗

    1小时前
    00
  • 取消Win10开机系统选择倒计时,让电脑秒进系统

    取消Win10开机系统选择倒计时,让电脑秒进系统 近期,不少Win10用户反映在开机时会遇到一个选择系统的倒计时画面,这在一定程度上延缓了开机进程。对于追求高效启动体验的用户来说,这无疑是一个不必要的步骤。那么,如何取消这个倒计时,让电脑

    1小时前
    00
  • PyMC+AI提示词贝叶斯项目反应IRT理论Rasch分析篮球比赛官方数据:球员能力与位置层级结构研究

    全文链接:tecdat?p=41666在体育数据分析领域不断发展的当下,数据科学家们致力于挖掘数据背后的深层价值,为各行业提供更具洞察力的决策依据。近期,我们团队完成了一项极具意义的咨询项目,旨在通过先进的数据分析手段,深入探究篮球比赛中

    58分钟前
    00
  • 聊聊Spring AI Alibaba的ObsidianDocumentReader

    序本文主要研究一下Spring AI Alibaba的ObsidianDocumentReaderObsidianDocumentReadercommunitydocument-readersspring-ai-alibaba-star

    57分钟前
    00
  • 我用AI监控了奥特曼,当他一发推特AI就会自动给我打电话。

    上周我真的扛不住了。奥特曼这个孙贼,发了个X说,“要发一个礼拜的好东西”。我信了他的邪,明明出差1周,每天早上9点不到就要起来参加活动,但是晚上根本不敢睡觉,天天蹲到凌晨3点半,蹲到他们那边时间中午12点多,我才敢去睡觉。真的,那一整周,我

    45分钟前
    00
  • 如何打造高效AI智能体?

    作者|Barry Zhang, Anthropic地址|出品|码个蛋(ID:codeegg)整理|陈宇明最近看到了 Anthropic 那篇著名的《Building effective agents》作者之一 Barry Zhang 在 2

    40分钟前
    00
  • 长读长测序揭示结直肠癌异常可变剪接图谱与新型治疗靶点

    徐州医科大学肿瘤研究所董东郑骏年教授团队在Genome Medicine杂志发表题为“Long-read sequencing reveals the landscape of aberrant alternative splicing

    33分钟前
    00
  • 国产车载通信测试方案:车规级CAN SIC芯片测试技术解析

    随着智能网联汽车的快速发展,车辆内部电子控制单元(ECU)数量激增,动力总成、高级驾驶辅助系统(ADAS)、车身控制等功能对车载通信网络的稳定性与速率提出了更高要求。传统CAN FD总线在复杂拓扑中面临信号振铃、通信速率受限(实际速率通常低

    31分钟前
    00
  • 开源在线考试系统

    看到调问已经开始扩展在线考试的场景,试了一下,发现在线考试的基本能力都已经支持了。主要是考试中的各种计分功能,包括对每道题的选项设置分值计算、考试时间限制等,和官方了解了一下,考试中的其他各项能力也在逐步完善,有需求可以随时

    24分钟前
    00
  • Power BI 无公式实现帕累托图表

    帕累托分析(Pareto Analysis),也被称为8020法则、关键少数法则,是一种常用的管理工具,用于识别和处理影响业务的主要因素。看到李伟坚老师在Excel使用Vega实现了花式帕累托(参考:Excel 零公式实现高级帕累托图表)

    22分钟前
    00
  • module &#x27;torch.

    踩坑Ascend, 安装 pytorch 2.5.1 和 pytorch_npu 2.5.1, import torch 报错.执行 python -c "import torch;import torch_npu;"时

    8分钟前
    10
  • 重装系统只影响C盘吗?深入解析系统重装的全过程

    重装系统只影响C盘吗?深入解析系统重装的全过程 在计算机的日常使用中,重装系统是一个常见的操作,尤其是在系统出现故障、感染病毒或需要优化系统性能时。然而,许多用户对于重装系统的具体过程和影响存在误解,认为重装系统仅仅是对C盘进行清空和重置

    6分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信