将可观察到的RxJS转换为承诺 [英] Converting RxJS Observable to a Promise

查看:78
本文介绍了将可观察到的RxJS转换为承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用多个http调用将数据存储在本地存储中.我使用forkJoin等待所有调用完成,然后再恢复Promise.then调用链.我该怎么做?

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

推荐答案

您可以使用Observable

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

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

编辑:作为 FriOne &注释中提到的 Lyubimov Roman ,请不要忘记

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

import 'rxjs/add/operator/toPromise';

这篇关于将可观察到的RxJS转换为承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆