Angular: $ q.defer () vs $ q ()

In Angular, the following snippets seem equivalent:

let deferred = $q.defer();
if(whatever) {
   deferred.resolve('something');
}
else {
   deferred.reject('nah');
}
return deferred.promise;

and

return $q((resolve,reject) => {
    if(whatever) {
       resolve('something');
    }
    else {
       reject('nah');
    }
});

My question is: if they are not equivalent, how do they differ? If they are equivalent, is there a good reason to prefer one over the other?

+4
source share
3 answers

The second version you posted is the next one, following the Promise / A + -Specification.

. ( ) , , ES2015, ES6, javascript.

, , .

+5

$q promises go, . , , native promises, , (, , , promises ).

, . native promises, Q promises, Bluebird promises , , , $q(). $q .

Bluebird promises , . , promises, $q:

function queryValue(callback) {
  throw new Error("Not implemented yet!!!");
}

function makeConstructorPromise() {
  return new Promise(function(resolve) {
    queryValue(function(value) {
      resolve(value);
    });
  });
}

function makeDeferredPromise() {
  let deferred = Promise.defer();

  queryValue(function(value) {
    deferred.resolve(value);
  });

  return deferred.promise;
}

makeConstructorPromise()
  .catch(function(error) {
    console.error('caught the constructed promise error!', error);
  });

makeDeferredPromise()
  .catch(function(error) {
    // not caught
    console.error('caught the deferred promise error!', error);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js"></script>

, 99% - .

( ) , ES6 promises.

+3

- "".

Kris Kowals Q, promises javascript.

, ES6.

, , - , ES6, " javascript", angular.

You can find additional information on this topic and your question directly in Angualar Docu: https://docs.angularjs.org/api/ng/service/ $ q /

0
source

All Articles