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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With