Angular 异步 HTTP 请求未异步发送

Angular Async HTTP requests not being send asynchronously

基本上我的问题是 - 我有 6 个不同的端点 return 不同的数字 - 我希望能够异步发送 6 个请求但是使用 chrome 工具我看到它们 运行顺序不异步。

  ngOnInit() {
    private readonly TEMP_URL: string = 'https://www.random.org/integers/?num=1&min=1&max=100000&col=1&base=10&format=plain&rnd=new';
    const result1 = this.http.get<Number>(this.TEMP_URL);
    const result2 = this.http.get<Number>(this.TEMP_URL);
    const result3 = this.http.get<Number>(this.TEMP_URL);
    const result4 = this.http.get<Number>(this.TEMP_URL);
    const result5 = this.http.get<Number>(this.TEMP_URL);
    const result6 = this.http.get<Number>(this.TEMP_URL);
    const result7 = this.http.get<Number>(this.TEMP_URL);


    forkJoin(result1,result2,result3,result4,result5,result6,result7).subscribe(results  => {
                    this.retVal0= results[0];
                    this.retVal1 = results[1];
                    this.retVal2 = results[2];
                    this.retVal3= results[3];
                    this.retVal4= results[4];
                    this.retVal5= results[5];
                    this.retVal6= results[6];
                    this.retVal7= results[7];
            });
  };

你的代码没问题,问题直接来自Chrome。通过检查请求,您可以看到它们已停滞/排队。如果您在另一个浏览器 (Firefox) 中进行相同的检查,您会看到请求是以异步方式发出的,没有排队。

Queued or Stalled Requests

Too many requests are being made on a single domain. On HTTP/1.0 or HTTP/1.1 connections, Chrome allows a maximum of six simultaneous TCP connections per host.

请记住,在 proxy 后面会降低最大同时请求数 - 这意味着即使有两个请求,您也可能会遇到停滞的请求。

糟糕的是,您无法通过编辑 Angular 代码来解决此问题。可能的修复仅包括网络设置修改:

  • 如果必须使用 HTTP/1.0 或 HTTP/1.1
  • ,请实施域分片
  • 使用HTTP/2。不要将域分片与 HTTP/2.
  • 一起使用
  • 删除或推迟 不必要的请求,以便关键请求可以更早下载

在您的示例中,您多次请求相同的资源。

Chrome 缓存响应并使用缓存锁定机制,在发送对同一资源的下一个请求之前检查缓存。

The cache implements a single writer - multiple reader lock so that only one network request for the same resource is in flight at any given time.

Note that the existence of the cache lock means that no bandwidth is wasted re-fetching the same resource simultaneously. On the other hand, it forces requests to wait until a previous request finishes downloading a resource (the Writer) before they can start reading from it, which is particularly troublesome for long lived requests. Simply bypassing the cache for subsequent requests is not a viable solution as it will introduce consistency problems when a renderer experiences the effect of going back in time, as in receiving a version of the resource that is older than a version that it already received (but which skipped the browser cache).

https://www.chromium.org/developers/design-documents/network-stack/http-cache

如果您在开发者工具中禁用缓存,您应该会看到同时发送的请求。

您还可以在每个 url:

的查询字符串中添加一些唯一编号
this.TEMP_URL + '?unique=<yourUniqueNumber>'