如何获得已经解决的承诺的价值? [英] How to get value of promise that already resolved?
问题描述
我有一个承诺,我将绑定到我的 UI 中.当承诺解决并且 UI 元素呈现时,我可以单击该 UI 元素.在我处理点击的控制器代码中,我想对承诺的价值采取行动.在我的角度代码的这一点上,我已经知道承诺已解决..但是当我想获得价值时,它仍然是一个承诺.
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?
推荐答案
承诺永远是承诺 - 这就是它们应该的样子.虽然可以将 promise 直接绑定到视图,但我通常不鼓励这种做法,因为它缺乏透明度并可能导致视图闪烁.更好的解决方案是在 then
调用中分配范围值:
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;
});
当 $scope.val
准备好时,它总是可以被直接视为一个值 - 因为它是.
When $scope.val
is ready, it can always be treated directly as a value - because it is.
也就是说,如果你想直接做promise赋值,你只需要把它当作一个promise;也就是说,你需要调用promise.then(function () { ... });
.这看起来很不方便,但实际上证明了 Promise 的强大.
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.
如果你想了解更多关于 promise 的信息,我在最近的一次 Google+ Hangout 中对它们进行了描述(并提供了代码示例),其中我介绍了 AngularJS 中 promise 的优点、常见用途和最佳实践:AngularJS Hangout -- 承诺,承诺承诺,承诺.永无止境的承诺链的想法得到了特别的解决,尽管我的脑海中没有时间码.
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.
希望这会有所帮助!
这篇关于如何获得已经解决的承诺的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!