equivalent of $q.when in angular 2

落爺英雄遲暮 提交于 2019-12-07 17:04:13

问题


I am used to using $q with angular 1. I am migrating to angular 2.

Is there an equivalent that provide a .when() method ?

for example I need to migrate this:

.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:


You can do the equivalent, with:

Promise.resolve(promise).then

Which basically makes no distinction between promises and values.

And yes you can instantiate q the same way, but with new Promise() rather than $q()

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

and

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

Should be equivalent



来源:https://stackoverflow.com/questions/43051414/equivalent-of-q-when-in-angular-2

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