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.
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.
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.
Thanks!
 
    