Javascript NestJs异步httpService调用
如何使用NestJs在Javascript NestJs异步httpService调用,javascript,node.js,typescript,nestjs,Javascript,Node.js,Typescript,Nestjs,如何使用NestJs在HttpService上使用Async/Await? 以下代码不起作用: async create(data) { return await this.httpService.post(url, data); } HttpModule使用ObservablenotPromise,它不适用于async/await。所有HttpService方法返回Observable 因此,您可以将其转换为Promise,然后在调用它时使用wait,或者只返回observeable
HttpService
上使用Async/Await?
以下代码不起作用:
async create(data) {
return await this.httpService.post(url, data);
}
HttpModule
使用Observable
notPromise
,它不适用于async/await。所有HttpService
方法返回Observable
因此,您可以将其转换为Promise
,然后在调用它时使用wait,或者只返回observeable
,让调用方处理它
create(data): Promise<AxiosResponse> {
return this.httpService.post(url, data).toPromise();
^^^^^^^^^^^^^
}
创建(数据):承诺{
返回此.httpService.post(url,数据).toPromise();
^^^^^^^^^^^^^
}
请注意,
return wait
几乎总是冗余的(try-catch除外) rxjs库是最强大的并发程序包,它选择了处理系统事件(如单击)、外部请求(如获取数据或删除记录)和
该库背后的主要概念是:
处理将来接收的数据
因此,在可观察的对象中,如
observablSource.subscribe(
data => { ... },
failure => { ... },
compelete => { ... }
)
但对于大多数后端开发人员来说,使用的承诺来自JavaScript,并且是JavaScript的本机部分
默认情况下,在和使用支持可观察的的rxjs。在技术细节中,您可以找到一个解决方案,使更改自动可观察到承诺
const data: Observable<any>;
data.from([
{
id: 1,
name: 'mahdi'
},
{
id: 2,
name: 'reza'
},
])
从这一步开始,您已经承诺使用对象和表单更好地附加async/await
异步用户列表(URL:string | URLPattern){
const userList=wait this.http.get(URL.toPromise();
...
}
以下是工作代码的完整示例: .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;
}
异步getAuthToken(){
常数有效载荷={
“范围”:this.configService.get('SCOPE'),
“EMAIL\u ID”:this.configService.get('EMAIL\u ID'),
“密码”:this.configService.get('PASSWORD'),
};
const url=this.configService.get('AUTHTOKEN\u url')
const response=等待this.httpService.post(
网址,
有效载荷
).toPromise();
console.log(response.data);
返回响应数据;
}
感谢您的帮助,Mahdi!我就是这么做的!
async userList( URL: string | URLPattern ) {
const userList = await this.http.get<any>( URL ).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;
}