简体   繁体   English

在 angular api 响应中异步和等待

[英]async and await in angular api response

I am trying to do task step by step.我正在尝试逐步完成任务。

I have a for loop in a method:我在一个方法中有一个 for 循环:

async changeTimeStep3() {
  for (let i = 1; i < 10; i++) {
    await this.do(i)
  }
}

for each step must do() task.对于每一步都必须做()任务。

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

  

I want to wait to get response and after response coming go to next i我想等待得到响应,然后响应 go 到下一个i

But not work console.log print:但不能工作 console.log 打印:

2
3
5
1
4
7
8
9
6

Note time to receive response from api is not fix.注意从 api 接收响应的时间不固定。

Any help?有什么帮助吗?

To get your loop print out the values in the correct order you could transform your observables into promises, so your await will block the for -loop as long as the HTTP call hasn't resolved.为了让您的循环以正确的顺序打印出值,您可以将您的 observables 转换为 Promise,因此只要 HTTP 调用尚未解决,您的await就会阻止for循环。

import { firstValueFrom } from 'rxjs';

...

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

Using firstValueFrom or lastValueFrom are the RxJS ways to get a promise as return value from an observable (since toPromise got deprecated, you can read more about that here ).使用firstValueFromlastValueFrom是 RxJS 方法来获取 promise 作为从 observable 的返回值(因为toPromise已被弃用,您可以在此处阅读更多相关信息)。

You can return a Promise and use resolve() in response part of your ajax.您可以返回Promise并在 ajax 的响应部分中使用resolve() Like:喜欢:

do(i) {
  return new Promise((resolve, reject) => {
    this.http.getDataFromServer("api/example?id=" +i).subscribe((response) => {
      resolve(response);
    }, (error) => {
      console.error(error);
      reject();
    });
  });
}

The problem here is that do is not an asynchronous method;这里的问题是 do 不是异步方法; it is a synchronous method that triggers an asynchronous one.它是一种触发异步方法的同步方法。 As such, the await completes immediately.因此,等待立即完成。

You may be able to do this:您可以这样做:

do(i) {
  return firstValueFrom(this.http
    .getDataFromServer(
      "api/example?id=" +i
    ))
}

It converts the observable into a promise and returns it.它将 observable 转换为 promise 并返回它。 So, now the do() method returns an async object.所以,现在 do() 方法返回一个异步 object。 To output from the do method;从do方法到output; you can use a pipe:您可以使用 pipe:

  return firstValueFrom(this.http
    .getDataFromServer(
      "api/example?id=" +i
    ).pipe(tap((result) => {console.log(i);}))

All that said, using async/await in Angular is unusual.综上所述,在 Angular 中使用 async/await 是不寻常的。 An RXJS operator is usually considered the right approach. RXJS 运算符通常被认为是正确的方法。 Possibly with concat可能与concat

Try this...尝试这个...

Make an promise out of it用它制作一个 promise

function do(i) {
  return new Promise((res) => {
    this.http.getDataFromServer("api/example?id=" + i).subscribe(res);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM