您好,即时通讯使用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;
}
但是,当我运行此代码时,这些值在控制台中返回为“ Resolved:undefined”。这使我相信await并没有停止post()函数中的程序。我在这里做错什么了?
答案 0 :(得分:4)
Angular的this.http.post
返回一个RxJS Observable。然后调用this.http.post(...).subscribe(...)
返回RxJS Subscription
对象。因此它们都不返回Promise,因此您不能将它们与await
一起使用。
如果您希望能够将await
与Observables一起使用,则必须使用toPromise()
而不是subscribe()
来返回由该Observable发出的第一个值解析的Promise(它在内部为您调用subscribe
,并用Promise
对象包装。)
await this.http.post(...).toPromise(value => {
...
});
https://github.com/ReactiveX/rxjs/blob/master/src/internal/Observable.ts#L342-L354