How to convert this deferred style promise to an ES6 style promise

Pay attention to the error Rookie # 4: the use of β€œdeferred” in Nolan Lawson : We have a problem with promises (By the way, a great post!), I no longer want to use the deferred style of promises. I recently came across a practical example that I can’t figure out how to NOT encode this in a delayed way, so I need some advice.

Here is an example, 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 (for example, the _modalScope implementation), the main idea: $modal provide a ui widget that contains two buttons: Confirm and Cancel strong>. When the Confirm button is clicked, call _modalScope.confirm and enable the deferred promise, otherwise reject the deferred promise by calling _modalScope.cancel when Cancel is clicked.

I tried to rewrite with 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 _modalScope.confirm/cancel . I have been struggling with this problem for several days, hope someone can help me.

Thanks!

+5
source share
1 answer

Assuming 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() } }); } } } 
+4
source

All Articles