在角度2中相当于$ q.when

时间:2017-03-27 16:10:48

标签: angular ionic2 observable deferred

我习惯使用角度为1的$q。我正在迁移到角度2。

是否有提供.when()方法的等效文件?

例如我需要迁移它:

.service('updateProDB', [
            '$rootScope',
            'connectionStatus',
            '$q',
            'storageService',
            'sendToServer',
            '$ionicPopup',
            function ($rootScope, connectionStatus, $q, storageService, sendToServer, $ionicPopup) {
                'use strict';

                var dbReadyDeferred = $q.defer(),
                prodata = [],
                prodataFieldNames = [];

            this.get = function () {
                var debugOptionUseLocalDB = 0,
                    prodata = [],
                    serverAttempts = 0;

                if (debugOptionUseLocalDB) {
                    return fallbackToLocalDBfileOrLocalStorageDB();
                }
                if (connectionStatus.f() === 'online') {
                    console.log("Fetching DB from the server:");
                    return getDBfileXHR(dbUrl(), serverAttempts)
                            .then(function () { // success
                                console.log('-normal XHR request succeeded.');
                                return dbReadyDeferred.promise;
                            })
                            .catch(function (){

1 个答案:

答案 0 :(得分:7)

您可以使用以下内容执行等效操作:

Promise.resolve(promise).then

这基本上不区分承诺和价值观。

是的,你可以用同样的方式实例化q,但使用new Promise()而不是$q()

let promise = Promise((resolve, reject) => {
    if (/* some async task */) {
       resolve('Success!');
    } else {
        reject('Oops... something went wrong');
    }
});

let promise = $q((resolve, reject) => {
    if (/* some async task */) {
       resolve('Success!');
    } else {
       reject('Oops... something went wrong');
    }
});

应该是等价的