Angular API 响应中的 async 和 wait

jac*_*ros 2 javascript asynchronous async-await typescript angular

我正在尝试一步一步地完成任务。

我的方法中有一个 for 循环:

async changeTimeStep3() {
  for (let i = 1; i < 10; i++) {
    await this.do(i)
  }
}
Run Code Online (Sandbox Code Playgroud)

每一步都必须执行 do() 任务。

do(i) {
  this.http
    .getDataFromServer(
      "api/example?id=" +i
    )
    .subscribe((response) => {
     console.log(i);
    });
}

  
Run Code Online (Sandbox Code Playgroud)

我想等待得到回复,回复后转到下一步i

但不能工作 console.log 打印:

2
3
5
1
4
7
8
9
6
Run Code Online (Sandbox Code Playgroud)

请注意,从 api 接收响应的时间不固定。

有什么帮助吗?

Bat*_*jus 8

为了让循环以正确的顺序打印出值,您可以将可观察量转换为承诺,因此只要 HTTP 调用尚未解析,您await就会阻塞循环。for

import { firstValueFrom } from 'rxjs';

...

async do(i: number) {
  await firstValueFrom(
    this.http
      .getDataFromServer(
        "api/example?id=" +i
      )
  );
  console.log(i);
}
Run Code Online (Sandbox Code Playgroud)

使用firstValueFromorlastValueFrom是 RxJS 方法,从可观察对象中获取 Promise 作为返回值(由于toPromise已弃用,您可以在此处阅读更多相关信息)。