如何在pipe()之后将observable转换为Promise



我有一个异步函数来获取数据。为了操作返回的数据,我使用from()将Promise转换为可观察的,并使用pipe()来操作数据。是否可以在pipe()之后将其转换回Promise?我尝试了以下方法,但没有成功:

getOrder() {
return from(asyncFunctionToGetOrder())
.pipe(map(data) =>
//Processing data here
return data;
))
.toPromise(); //This won't work
}

我不知道你为什么要返回promise,为什么在获取数据时不能转换为promise,请参阅:

this.getOrder()
.toPromise()
.then((response:any) => {
this.records = response;
}).catch(error => {
console.log(error)
}).finally(() => {
// code to cleanup
});

无可观测:

getOrder() {
return asyncFunctionToGetOrder().then(
(data) => {
// Processing data here
return Promise.resolve(data);
}
);
}

不过它应该可以工作。

请记住,toPromise仅在可观察到的完成时返回。此外,如果你的承诺被拒绝,你需要抓住错误。

为您举一个例子:https://stackblitz.com/edit/rxjs-4n3y41

import { of, from } from 'rxjs'; 
import { map, catchError } from 'rxjs/operators';

const fetchCall = () => {
return Promise.resolve({a: 1, b: 2});
}
const problematicCall = () => {
return Promise.reject('ERROR')
}
const transformedPromise = from(fetchCall())
.pipe(map(data => data.a))
.toPromise()
const problematicTransformed = from(problematicCall())
.pipe(catchError(data => of(data)))
.toPromise()

transformedPromise.then((a) => console.log('Good boy', a));
problematicTransformed.then((a) => console.log('Bad boy', a));

最新更新