简体   繁体   English

NestJs 异步 httpService 调用

[英]NestJs async httpService call

How can I use Async/Await on HttpService using NestJs?如何使用 NestJs 在HttpService上使用 Async/Await? The below code doesn`t works:以下代码不起作用:

async create(data) {
    return await this.httpService.post(url, data);
}

The HttpModule uses Observable not Promise which doesn't work with async/await. HttpModule使用Observable而不是Promise ,它不适用于 async/await。 All HttpService methods return Observable<AxiosResponse<T>> .所有HttpService方法都返回Observable<AxiosResponse<T>>

So you can either transform it to a Promise and then use await when calling it or just return the Observable and let the caller handle it.因此,您可以将其转换为Promise ,然后在调用它时使用 await,或者只返回Observable并让调用者处理它。

create(data): Promise<AxiosResponse> {
    return this.httpService.post(url, data).toPromise();
                                           ^^^^^^^^^^^^^
}

Note that return await is almost (with the exception of try catch) always redundant.请注意, return await几乎(除了 try catch)总是多余的。

Update 2022 2022 年更新

toPromise is deprecated. toPromise已弃用。 Instead, you can use firstValueFrom :相反,您可以使用firstValueFrom

import { firstValueFrom } from 'rxjs';

// ...

return firstValueFrom(this.httpService.post(url, data))

As toPromise() is being deprecated, you can replace it with firstValueFrom or lastValueFrom由于toPromise()已被弃用,您可以将其替换为firstValueFromlastValueFrom

For example:例如:

const resp = await firstValueFrom(this.http.post(`http://localhost:3000/myApi`)

https://rxjs.dev/deprecations/to-promise https://rxjs.dev/deprecations/to-promise

rxjs library is most powerful concurrency package that chosen form handling system event like click, external request like get data or delete record and .... rxjs 库是最强大的并发包,它选择表单处理系统事件(如点击)、外部请求(如获取数据或删除记录)和....

The main concept behind this library is:这个库背后的主要概念是:

handle data that receive in future处理将来接收的数据

therefor you most use 3 argument in observable object like因此,您最常在可观察对象中使用 3 个参数,例如

observablSource.subscribe(
   data => { ... },
   failure => { ... },
   compelete => { ... }
)

but for most backend developer use Promises that comes from ECMAScript 6 feature and is native part of JavaScript.但是对于大多数后端开发人员来说,使用来自ECMAScript 6 特性并且是 JavaScript 的本机部分的Promises

By default in Angular 4+ and Nest.js use rxjs that support Observable .默认情况下, Angular 4+Nest.js使用支持Observablerxjs In technical details you can find a solution for change automatic observable to promise.在技​​术细节中,您可以找到将可观察到的自动更改为承诺的解决方案。

const data: Observable<any>;
data.from([
   {
      id: 1,
      name: 'mahdi'
   }, 
   {
      id: 2,
      name: 'reza'
   },
 ])

now you have simulate a request with observable type from server.现在您已经模拟了来自服务器的可观察类型的请求。 if you want to convert it to Pormise use chained method like example:如果要将其转换为Pormise ,请使用链式方法,例如:

   data.toPromise();

from this step you have promised object and form using it better to attach async/await从这一步开始,您已经承诺使用它更好地附加async/await的对象和表单

 async userList( URL: string | URLPattern ) {
    const userList = await this.http.get<any>( URL ).toPromise();
    ...
 }

try these below one instead of only async-await.试试下面的这些,而不是仅仅 async-await。

There are some basic reasons behind the deprecation of toPromise.弃用 toPromise 背后有一些基本原因。

We know that Promise and Observables that both collections may produce values over time.我们知道 Promise 和 Observables 这两个集合都可能随着时间的推移产生价值。 where Observables return none or more and Promise return only one value when resolve successfully.其中 Observables 不返回或返回更多,而 Promise 在解析成功时只返回一个值。

there is a main reason behind the seen看到的背后有一个主要原因

Now we have 2 new functions.现在我们有 2 个新功能。

Following is complete example for working code:以下是工作代码的完整示例:

.toPromise() is actually missing .toPromise() 实际上是缺失的

async getAuthToken() {
    const payload = {
      "SCOPE": this.configService.get<string>('SCOPE'),
      "EMAIL_ID": this.configService.get<string>('EMAIL_ID'),
      "PASSWORD": this.configService.get<string>('PASSWORD'),
    };
    const url = this.configService.get<string>('AUTHTOKEN_URL')
    const response = await this.httpService.post(
      url,
      payload
    ).toPromise();
    console.log(response.data);
    return response.data;
  }

You can just add the .toPromise() at the end of each method call but then you lose the power of observables, like it's ability to add retry to failed http call by just adding the retry operator.你可以在每个方法调用的末尾添加 .toPromise() ,但是你失去了 observables 的力量,就像它能够通过添加重试运算符来为失败的 http 调用添加重试。

You can implement this abilities by yourself and create your own module or just use package that already implemented it like this : https://www.npmjs.com/package/nestjs-http-promise您可以自己实现此功能并创建自己的模块,或者只使用已经实现它的包,如下所示: https ://www.npmjs.com/package/nestjs-http-promise

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

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