Jos*_*bor 8 async-await rxjs angular-promise angular angular6
您好,即时通讯使用angular 6使用以下代码调用rest api。我试图使代码与async-await函数同步。但是缺少什么
async save() {
if (this.changedRecords.length !== 0) {
this.post('/api/devices/update-devices', this.changedRecords).
then(x => { console.log("change"); console.log(`Resolved: ${x}`) });
}
if (this.newRecords.length !== 0) {
this.post('/api/devices/new-devices', this.newRecords).
then(x => { console.log("new"); console.log(`Resolved: ${x}`) });
}
if (this.deletedRecords != null) {
this.post('/api/devices/delete-devices', this.deletedRecords).
then(x => { console.log("deleted"); console.log(`Resolved: ${x}`) });
}
}
async post(url: string, list: DboDevice[]) {
var result;
if (list.length !== 0) {
await this.http.post(url, list).subscribe(result => {
result = true;
}, error => {
console.error(error);
result = false;
});
}
else {
result = true;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,这些值在控制台中返回为“ Resolved:undefined”。这使我相信await并没有停止post()函数中的程序。我在这里做错了什么?
mar*_*tin 13
Angular的this.http.post
返回RxJS Observable。然后调用this.http.post(...).subscribe(...)
返回RxJS Subscription
对象。因此,它们都不返回Promise,因此您不能将它们与一起使用await
。
如果您希望能够await
与Observable 一起使用,则必须使用它toPromise()
而不是subscribe()
返回一个Promise,该Promise将使用该Observable发出的第一个值进行解析(它在内部调用subscribe
您并将其包装为一个Promise
对象)。
await this.http.post(...).toPromise(value => {
...
});
Run Code Online (Sandbox Code Playgroud)
https://github.com/ReactiveX/rxjs/blob/master/src/internal/Observable.ts#L342-L354
归档时间: |
|
查看次数: |
6959 次 |
最近记录: |