I am seeing angularJS files where in some places reviewer has mented these 3 lines:
var deferred = $q.defer();
deferred.resolve(BrandList);
return deferred.promise;
and replaced with this one:
return $q.when(BrandList);
I would like to understand the difference between two. Do both serve same purpose? Which should be used when?
I am seeing angularJS files where in some places reviewer has mented these 3 lines:
var deferred = $q.defer();
deferred.resolve(BrandList);
return deferred.promise;
and replaced with this one:
return $q.when(BrandList);
I would like to understand the difference between two. Do both serve same purpose? Which should be used when?
Share Improve this question edited Jul 6, 2015 at 17:14 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Jul 6, 2015 at 17:06 Devesh AgrawalDevesh Agrawal 9,22218 gold badges86 silver badges134 bronze badges 3- Yes, they do the same. But only the second conveys the intent (and it's shorter as well). – Bergi Commented Jul 6, 2015 at 17:16
- So can we use either of two at any point of time in our code?? – Devesh Agrawal Commented Jul 6, 2015 at 17:20
-
Well,
$q.when
is a single function, and could be passed around. A call to it makes a single expression that can be used about everywhere, while the first snippet with$q.defer()
contains multiple statements. – Bergi Commented Jul 6, 2015 at 17:22
2 Answers
Reset to default 4Ben Nadal does a great job of explaining this here.
In his words:
The $q.when() method doesn't just create a promise that is immediately resolved; rather, it normalizes a value that may or may not be a "thenable" object. If the given value is a promise, $q.when() will properly chain off of it. If the given value is not a promise, $q.when() will create promise resolved with the given value.
So essentially it takes either promises or non-promises and does some magic to make sure they are either resolved or promise wrapped so as not to break the promise chain.
$q.defer()
is appropriate when you want to decorate a function to use promises instead of callbacks. Usually, you will specify a deferred.resolve()
and a deferred.reject()
, and maybe even a deferred.notify()
.
$q.when()
is appropriate when you want to immediately create a new promise and resolve it to a value. EDIT it also normalizes variables into promises, which is useful if the variable may or may not be a promise. See Jim's answer.
$q.when()
seems to be appropriate for your case.