Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: $q.defer() vs $q() [duplicate]

In Angular, the following snippets seem to be 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: if they aren't equivalent, how do they differ? If they are equivalent, is there a compelling reason for preferring one over the other?

like image 608
csvan Avatar asked Feb 07 '23 12:02

csvan


1 Answers

The second version that you posted is the one that follows the Promise/A+-Specification.

From a functional perspective, both versions are equivalent. The first version (in my eyes) makes it easier to read the asynchronous code as synchronous one, but the second one uses the syntax that has made it into ES2015 and will also be part of ES6, i.e. the next versions of javascript.

Thus, the choice is up to you, but you can expect to see a lot more of the second type of promise-syntax in the future.

like image 182
burnedikt Avatar answered Feb 10 '23 23:02

burnedikt