Make sure to take a look at Rookie mistake #4: using "deferred" in Nolan Lawson's insightful article titled We have a problem with promises (which is definitely worth the read). I used to rely on deferred style promises, but after reading this, I'm trying to avoid them. However, I recently encountered a specific example where I can't seem to figure out an alternative method and find myself compelled to code using deferred. Any advice would be greatly appreciated.
Let's take a look at 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've omitted some details unrelated to this discussion (such as the implementation of _modalScope
), but essentially, the concept is: $modal
provides a UI widget with two buttons - Confirm and Cancel. Clicking Confirm calls _modalScope.confirm
to resolve the deferred promise, while clicking Cancel calls _modalScope.cancel
to reject it.
I attempted rewriting it using
return $q(function(resolve, reject) { ... })
, but I'm unsure of when and how to call resolve
and reject
within this constructor since the actual logic resides in the _modalScope.confirm/cancel
methods. I've been grappling with this issue for days and would really appreciate some assistance.
Thank you!