sthomps sthomps - 4 months ago 22
AngularJS Question

How to get value of promise that already resolved?

I have a promise that I am binding to in my UI. When the promise resolves and the UI element renders I can then click on that UI element. In my controller code where I handle the click I would like to act on the value of the promise. At this point in my angular code I already know that the promise is resolved.. but when I want to get the value its still a promise.

Whats the best way to get the value of the promise... given that I know it must have resolved?

Answer

Promises are always promises - and that's how they should be. While it is possible to bind a promise directly to the view, I generally discourage this practice because it lacks transparency and can lead to view flickering. A better solution is to assign a scope value in a then call:

myService.then(function( val ) {
  $scope.val = val;
});

When $scope.val is ready, it can always be treated directly as a value - because it is.

That said, if you want to do the promise assignment directly, you just have to treat it like a promise; that is, you need to call promise.then(function () { ... });. This seems like an inconvenience, but it's actually a testament to just how powerful promises are.

If you want some more info on promises, I pontificated on them (and provided code examples) for a recent Google+ Hangout, where I covered the advantages, common uses, and best practices of promises in AngularJS: AngularJS Hangout -- Promises, Promises Promises, Promises. The idea of never-ending promise chains was specifically addressed, though I don't have a timecode off the top of my head.

Hope this helps!