Refer to Rookie mistake #4: using "deferred" in Nolan Lawson's article: We have a problem with promises (btw a great post!), I try not to use deferred style promises anymore. Recently I've encountered a practical example that I can't figure out how to NOT code this in deferred way, so I need some advices.
参考新秀的错误#4:在Nolan Lawson的文章中使用“deferred”:我们有一个承诺的问题(顺便说一句很棒的帖子!),我尽量不再使用延迟风格的承诺。最近我遇到了一个实际的例子,我无法弄清楚如何以延迟的方式编码,所以我需要一些建议。
Here is the example, an angular factory:
这是一个角度工厂的例子:
function ConfirmModal($q, $modal) {
return {
showModal: function _showModal(options) {
var _modal = $modal(options)
var deferred = $q.defer()
_modalScope.confirm = function(result) {
deferred.resolve(result)
_modal.hide()
}
_modalScope.cancel = function(reason) {
deferred.reject(reason)
_modal.hide()
}
return deferred.promise
}
}
}
I hide some unrelated details(eg. implementation of _modalScope
), the core idea is: $modal
provide a ui widget which contains two button: Confirm and Cancel. When Confirm is been clicked, call _modalScope.confirm
and resolve the deferred promise, otherwise reject the deferred promise by calling _modalScope.cancel
when Cancel is been clicked.
我隐藏了一些不相关的细节(例如_modalScope的实现),核心思想是:$ modal提供一个ui小部件,其中包含两个按钮:Confirm和Cancel。单击“确认”后,调用_modalScope.confirm并解析延迟的promise,否则在单击“取消”时通过调用_modalScope.cancel来拒绝延迟的promise。
I tried to rewrite by using return $q(function(resolve, reject) { ... })
, but I really don't know how/when to call resolve
and reject
in this constructor, because the real logic is in the _modalScope.confirm/cancel
method. I'm struggled with this problem for days, really hope someone can help me.
我尝试使用return $ q(function(resolve,reject){...})重写,但我真的不知道在这个构造函数中如何/何时调用resolve和reject,因为真正的逻辑在_modalScope中.confirm / cancel方法。几天来我一直在努力解决这个问题,真的希望有人可以帮助我。
Thanks!
1 个解决方案
#1
5
Presuming the code in your questions is functional and _modalScope
is accessible from the _showModal()
function, then the code below should answer your question:
假设您的问题中的代码是可用的,并且可以从_showModal()函数访问_modalScope,那么下面的代码应该回答您的问题:
function ConfirmModal($q, $modal) {
return {
showModal: function _showModal(options) {
return $q(function(resolve, reject) {
var _modal = $modal(options)
_modalScope.confirm = function(result) {
resolve(result)
_modal.hide()
}
_modalScope.cancel = function(reason) {
reject(reason)
_modal.hide()
}
});
}
}
}
#1
5
Presuming the code in your questions is functional and _modalScope
is accessible from the _showModal()
function, then the code below should answer your question:
假设您的问题中的代码是可用的,并且可以从_showModal()函数访问_modalScope,那么下面的代码应该回答您的问题:
function ConfirmModal($q, $modal) {
return {
showModal: function _showModal(options) {
return $q(function(resolve, reject) {
var _modal = $modal(options)
_modalScope.confirm = function(result) {
resolve(result)
_modal.hide()
}
_modalScope.cancel = function(reason) {
reject(reason)
_modal.hide()
}
});
}
}
}