我如何推迟像 jquery Deferred 这样的 ES6 promise?

How do I defer an ES6 promise like jquery Deferred?

1。使用es6 promise,但是语法不正确

我正在使用 es6,并且想制作一个延迟确认对话框:

// 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(); })

当我点击按钮时,它失败了,因为 promise 没有 rejectresolve 方法。

Uncaught TypeError: promise.resolve is not a function(…)

2。 jQuery 工作代码:

如果使用jQuery,我们可以执行以下操作:

// 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(); })

3。尝试为 es6 找到延迟接口。

所以我搜索了一个 ES6 EDITION of deferred:

https://github.com/seangenabe/es6-deferred

但我仍然得到一个错误:

undefined:1 Uncaught (in promise) Object {}

实际上,代码只是使用闭包将内部的resolvereject函数保留在外部:

https://github.com/seangenabe/es6-deferred/blob/master/deferred.js

同样的策略,如果我这样做:

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(); })

那么,如何从我的承诺创建调用中提取 resolvereject 操作?

在 promise

中移动 jquery 语句
let promise = new Promise((resolve, reject) => {
 let $dialog = $('#dialog-confirm').show();
$dialog.find('.btn-yes').click(() => { resolve(); })
$dialog.find('.btn-no').click(() => { reject(); })

})
var Deferred = require('es6-deferred');
var d = new Deferred(
     (resolve, reject) => {
         // Process your Async or sync process here and
         // call resolve() and pass your data as argument when
         // it is successful
         // same for error case, just call reject() instead.
     }
);

d.then(
    (res) => {
    // res is your data passed into the resolve method the deferred promise
    // Handle your click here
    }, (err) => {
    // err is your data or error passed into the reject method
    // Handle your click here
  }
);

对于那些从 Google 来到这里的人来说,值得一提的是 ES6 承诺很好,我经常使用它们。但是,在某些用例中,延迟模式会导致代码显着减少。在大多数情况下,您应该只使用 ES6 promise,但在延迟模式有意义的特殊情况下,包装 ES6 promise 就足够容易了。在我看来,包含一个节点模块似乎太过分了。

function generateDeferredPromise() {
  let resolve, reject;
  const promise = new Promise((res, rej) => {
    [resolve, reject] = [res, rej];
  });
  return {promise, reject, resolve};
}