Converting RxJS Observable to a Promise

╄→гoц情女王★ 提交于 2019-12-08 16:27:43

问题


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);
}

回答1:


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';


来源:https://stackoverflow.com/questions/39022048/converting-rxjs-observable-to-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!