resolving a promise multiple times.

5,325 views
Skip to first unread message

James Wanga

unread,
Nov 29, 2012, 3:04:15 PM11/29/12
to ang...@googlegroups.com
I want to trigger a callback each time the promise is resolved. In the following example resolving a promise inside of a setInterval does not work. Can this be done? Thanks!


Ben Nadel

unread,
Nov 29, 2012, 3:16:10 PM11/29/12
to ang...@googlegroups.com
I created an augmentation of Deferred that does this:

https://github.com/bennadel/DeferredWithUpdate.js

Basically, it adds two more hooks - update / mistake.

I hope that helps,
Ben Nadel

ThomasBurleson

unread,
Nov 29, 2012, 4:59:49 PM11/29/12
to ang...@googlegroups.com
Here is the correct way to use promises with 

$rootScope.$apply( function() {
  deferred.resolve( incremented );
});

or use $timeout instead of setInterval.

See the following fiddle for details:  http://jsfiddle.net/ThomasBurleson/QqKuk/

ThomasBurleson

unread,
Dec 1, 2012, 12:29:57 PM12/1/12
to ang...@googlegroups.com

ThomasBurleson

unread,
Dec 2, 2012, 12:50:33 AM12/2/12
to ang...@googlegroups.com
Using futures [when.js, q.js, AngularJS $q, jQuery.defer(), etc.] provides 

1) a deferred instance which can be resolved or rejected
2) a promise from that deferred which is READ-only.
3) will fire any attached resolved or rejected handler 1x; even if attached are the resolve/reject action.

Your extensions to $q distort the $q specification in a very disturbing way. Your promise can modify the deferred `value`. 
This seems to be in violation of the standard that Promises are read-only. As such, I highly recommend that you avoid using your extension.

AngularJS $q has a unique feature in that a promise can be assigned to as a scope property and later it will resolve/reject as the resolved/rejected value.  

|  $q promises are recognized by the templating engine in angular, which means that in templates
|  you can treat promises attached to a scope as if they were the resulting values.

Since this features is unique to AngJS templating/scopes, I recommend that it should also be avoided ;-)

So the question remains, "How do I used client-side data as a temporary placeholder to a remote data request?"

And the answer is remarkably easy. 

1) Do not assign promises to scope properties; assign client-side data values
2) Use resolved handlers to update the scope properties.

I created a a jsFiddle to highlight some ideas:


Do you have a specific example where my solution - conformant to $q standards - will not work ?

Stuart Robinson

unread,
Jun 4, 2014, 5:54:55 AM6/4/14
to ang...@googlegroups.com
You could use the new notify syntax: http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/

I've got this working for a neat way of working with SignalR...
Reply all
Reply to author
Forward
0 new messages