How to convert a promise to rxjs since 7 #6830
Replies: 2 comments 3 replies
-
Hi @willin I just checked and the code that you shared works just fine. However, you probably wanted to do this instead: import { catchError, defer } from 'rxjs';
const fn = () => Promise.reject('test');
defer(fn).pipe(
catchError((err) => {
console.log('errored');
throw err;
})
); Because the code above delays the creation of the Promise rejection until there is a subscription on the created Observable. Please notice that the code that you shared is equivalent to const fn = () => Promise.reject('test');
from(fn()).pipe(
catchError((err) => {
console.log('errored');
throw err;
})
).subscribe({
error(e) {
console.log('handling the exception, all good!', e)
}
}) Then you wouldn't get the |
Beta Was this translation helpful? Give feedback.
-
i tried your codes and works. thx. however mine not working: import { Observable, defer, from, catchError } from 'rxjs';
export async function toPromise<T>(fn: (...arg: any[]) => Observable<T> | Promise<T>, args: any[] = []): Promise<T> {
defer(fn).pipe(
catchError((err) => {
throw err;
})
);
// eslint-disable-next-line no-return-await
return await new Promise((resolve, reject) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
from(fn(...args) as any)
.pipe(
catchError((err) => {
throw err;
})
)
.subscribe({
next: (val) => resolve(val as T),
error: (error) => reject(error)
});
});
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Errored with:
source at:
https://github.com/willin/v0/blob/main/src/utils/helpers.ts#L11
works previously however now cant, and i have no idea why
Beta Was this translation helpful? Give feedback.
All reactions