I'm using es6, and want to make a deferred confirm dialog:
// First, create an empty promise:
let promise = new Promise((resolve, reject) => {})
// Then, show the dialog:
let $dialog = $('#dialog-confirm').show();
// FAIL: I want to trigger the promise resolver, but failed.
$dialog.find('.btn-yes').click(() => { promise.resolve(); })
$dialog.find('.btn-no').click(() => { promise.reject(); })
When I clicked the button, it failed, because the promise does not have the reject
and resolve
method.
Uncaught TypeError: promise.resolve is not a function(…)
If using jQuery, we can do the below:
// First, create an empty promise:
var dfd = $.Deferred();
var promise = dfd.promise();
// Then, show the dialog:
var $dialog = $('#dialog-confirm').show();
// SUCCESS: jQuery deferred works
$dialog.find('.btn-yes').click(() => { dfd.resolve(); })
$dialog.find('.btn-no').click(() => { dfd.reject(); })
So I searched for an ES6 EDITION of deferred:
https://github.com/seangenabe/es6-deferred
But still I got an error:
undefined:1 Uncaught (in promise) Object {}
In fact, the code is just keep the inner resolve
and reject
function to outside using closure:
https://github.com/seangenabe/es6-deferred/blob/master/deferred.js
The same strategy if I do:
let dfd = {};
let $dialog = $('#dialog-confirm').show();
let promise = (function() {
return dfd.promise = new Promise(function(resolve, reject) {
dfd.resolve = resolve;
dfd.reject = reject;
});
})();
// FAIL: still not working.
$dialog.find('.btn-yes').click(() => { dfd.resolve(); })
$dialog.find('.btn-no').click(() => { dfd.reject(); })
So, how can I pull out the resolve
and reject
action out of my promise creation call?
For those of you getting here from Google its worth mentioning that ES6 promises are good and I use them a lot. However, there are use cases where the deferred pattern results in significantly less code. In most cases you should likely just use the ES6 promises but in those special cases where the deferred pattern makes sense then its easy enough to wrap an ES6 promise. Including a node module seems like over kill in my mind.
function generateDeferredPromise() {
let resolve, reject;
const promise = new Promise((res, rej) => {
[resolve, reject] = [res, rej];
});
return {promise, reject, resolve};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With