Learn RxJS
Search…
toPromise

signature: toPromise() : Promise

Convert observable to promise.

toPromise is not a pipable operator, as it does not return an observable.
[![Ultimate RxJS](https://drive.google.com/uc?export=view&id=1qq2-q-eVe-F_-d0eSvTyqaGRjpfLDdJz "Ultimate RxJS")](https://ultimatecourses.com/courses/rxjs?ref=4)

Examples

Example 1: Basic Promise
1
//return basic observable
2
const sample = val => Rx.Observable.of(val).delay(5000);
3
//convert basic observable to promise
4
const example = sample('First Example')
5
.toPromise()
6
//output: 'First Example'
7
.then(result => {
8
console.log('From Promise:', result);
9
});
Copied!
Example 2: Using Promise.all
1
//return basic observable
2
const sample = val => Rx.Observable.of(val).delay(5000);
3
/*
4
convert each to promise and use Promise.all
5
to wait for all to resolve
6
*/
7
const example = () => {
8
return Promise.all([
9
sample('Promise 1').toPromise(),
10
sample('Promise 2').toPromise()
11
]);
12
};
13
//output: ["Promise 1", "Promise 2"]
14
example().then(val => {
15
console.log('Promise.all Result:', val);
16
});
Copied!

Additional Resources

Last modified 1yr ago