Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting RxJS Observable to a Promise

I'm trying to store data in local storage using multiple http calls. I use forkJoin to wait until all of the calls have been completed and then I want to resume my Promise.then call chain. How do I do this?

updateCache() {
    var cachesToUpdate;

    return this.fetchServerTimestamps()
        .then(res => {
            var localTimestamps = this.getLocalTimestamps();
            var serverTimestamps = this.getServerTimestamps();

            //Compare timestamps and decide which cache data types to update
            cachesToUpdate = this.cacheTypes.filter(function (cacheType) {
                return localTimestamps ? localTimestamps[cacheType.timestamp] != serverTimestamps[cacheType.timestamp] : true;
            });
        }).then(res => {
            //Request data and insert into cache
            this.fetchData(cachesToUpdate)
                .subscribe(res => {
                    res.forEach(function (item, index) {
                        this.insert(cachesToUpdate[index].messageType, JSON.stringify(item));
                    }.bind(this));
                });
        });
}

fetchData(cachesToUpdate): Observable<any> {
    return forkJoin(cachesToUpdate.map(i => this.callservice.serverRead({ path: 'api/' + i.messageType })));
}

insert(key: string, value: string, compress = true) {
    localStorage.setItem(key, compress ? LZString.compress(value) : value);
}
like image 344
David Kuzmin Avatar asked Aug 18 '16 15:08

David Kuzmin


People also ask

How do you turn an Observable into a Promise?

How to Convert an Observable to a Promise in Angular? Since the get method of HttpClient returns an observable, we use the toPromise() method to convert the observable to a promise. Since you can convert an observable to a promise, you can make use of the async/await syntax in your Angular code.

Is a Promise better than an Observable?

Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.

Is Observable same as Promise?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time.

Do observables replace Promises?

While an Observable can do everything a Promise can, the reverse is not true. For example, an Observable can emit multiple values over time. A Promise only resolves once.


1 Answers

You can use toPromise() method of an Observable

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/topromise.md

this.fetchData(cachesToUpdate).toPromise().then(...)

Edit: as FriOne & Lyubimov Roman mentioned in the comment, don't forget to

import 'rxjs/add/operator/toPromise';
like image 149
Andrei Zhytkevich Avatar answered Oct 12 '22 17:10

Andrei Zhytkevich