'rxjs5 toPromise not working
In the following example toPromise
does not work:
https://jsfiddle.net/tossp/nmf9jg32/
My code:
function getPostData() {
return fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
}
var source = Rx.Observable.fromEvent(document.body, 'click');
var example = source.concatMap(
e => Rx.Observable.from(getPostData()),
(e, res, eIndex, resIndex) => res.title);
example.subscribe({
next: (value) => { console.log('subscribe!!!',value); },
error: (err) => { console.log('Error: ' + err); },
complete: () => { console.log('complete'); }
});
example.do((value)=>console.log('do!!!',value)).toPromise().then((value)=>console.log('toPromise!!!',value));
Solution 1:[1]
Already solved https://github.com/ReactiveX/rxjs/issues/2536
toPromise
is essentially observable.last().subscribe()
If you add .take(1)
just before you call toPromise
then things will start to work.
ie
example.do((value)=>console.log('do!!!',value)).take(1).toPromise()
Solution 2:[2]
In newer versions you must use take(1)
inside pipe()
. I did this kind of code:
async getPromise() {
return await example
.pipe(take(1))
.toPromise();
}
Hope it helps someone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TossPig |
Solution 2 |