本文介绍了我该如何延缓像jerr Deferred这样的ES6承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用es6,并希望创建一个延迟确认对话框:

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

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

When I clicked the button, it failed, because the promise does not have the reject and resolve method.

2. jQuery工作代码:

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

2. jQuery working code:

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

3.尝试找到es6的延迟接口.

所以我搜索了 ES6版本的延期:

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

但仍然出现错误:

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

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

那么,如何从我的Promise创建调用中退出resolvereject动作?

So, how can I pull out the resolve and reject action out of my promise creation call?

推荐答案

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

这篇关于我该如何延缓像jerr Deferred这样的ES6承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 09:39