您好,我使用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()函数中的程序。我在这里做错了什么?
发布于 2018-12-07 00:58:39
Angular的this.http.post返回一个RxJS Observable。然后调用this.http.post(...).subscribe(...)返回RxJS Subscription对象。所以它们都没有返回Promise,所以你不能在await中使用它们。
如果您想在可观察对象中使用await,则必须使用toPromise()而不是subscribe(),后者返回一个Promise,该Promise由该可观察对象发出的第一个值解析(它在内部为您调用subscribe并将其包装在一个Promise对象中)。
await this.http.post(...).toPromise(value => {
...
});https://github.com/ReactiveX/rxjs/blob/master/src/internal/Observable.ts#L342-L354
https://stackoverflow.com/questions/53656059
复制相似问题