Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert this deferred style promise to ES6 style promise

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!

like image 996
nightire Avatar asked Jun 27 '15 15:06

nightire


1 Answers

Presuming the code in your questions is functional and _modalScope is accessible from the _showModal() function, then the code below should answer your question:

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()
                }
            });
        }
    }
}
like image 129
JME Avatar answered Oct 13 '22 05:10

JME