将jQuery Deferred Promise转换为本地JavaScript Promise



我从库中提取了下面的JavaScript代码,它使用了jQuery的Deferred/Promise,这与官方的Promise规范不同。

我想将这个基本示例转换为Native JavaScript Promise,同时保持下面相同的格式/结构。

我在网上找到的几乎每一个Promise使用示例都是异步加载的,我有一些情况下我想将它们用于其他任务,而这个示例就是这样做的!

调用
  • App.show()
  • App.show()调用返回PromiseApp.Animations.swipe.apply(this, [current, next, dir]).then(finalize);的函数
  • promise函数内部有一个事件处理程序函数,该函数在CSS动画完成时运行,并触发promise进行解析
  • 当promise解析时,它调用App.show()函数内部的finalize函数

只需看看下面的例子,可能会更容易理解它的作用。。。。

var App = {
show: function(index, direction) {
var $this = this;
// called after Promise is resolved with .then(finalize)
finalize = function() {
// other code here ran now after promise resolved from App.Animations.swipe()....
};
// call function which returns a Promise
Animations.swipe.apply(this, [current, next, dir]).then(finalize);
},

Animations = {
'none': function() {
var d = UI.$.Deferred();
d.resolve();
return d.promise();
},
// function returns a Promise which has an event handler inside it that resolves the promise
'swipe': function(current, next, dir) {
var d = UI.$.Deferred();
next.css('animation-duration', this.options.duration + 'ms');
// Event handler ran one time when CSS Animation ends and triggers the event
// this event is what resolves the promise
next.css('opacity', 1).one(UI.support.animation.end, function() {
current.removeClass(dir === -1 ? 'uk-slideshow-swipe-backward-out' : 'uk-slideshow-swipe-forward-out');
next.css('opacity', '').removeClass(dir === -1 ? 'uk-slideshow-swipe-backward-in' : 'uk-slideshow-swipe-forward-in');
d.resolve();
}.bind(this));
// return a Promise Object when this function is called
return d.promise();
},
}
};

那么,基于该代码,如何将其转换为不使用jQuery的Deferred并使用本地JS Promises?

'none': function() {
var d = UI.$.Deferred();
d.resolve();
return d.promise();
},

这是一个简单的

'none': function() {
return Promise.resolve();
},

现在刷:

'swipe': function(current, next, dir) {
return new Promise(function(resolve, reject) {
next.css('animation-duration', this.options.duration + 'ms');
// Event handler ran one time when CSS Animation ends and triggers the event
// this event is what resolves the promise
next.css('opacity', 1).one(UI.support.animation.end, function() {
current.removeClass(dir === -1 ? 'uk-slideshow-swipe-backward-out' : 'uk-slideshow-swipe-forward-out');
next.css('opacity', '').removeClass(dir === -1 ? 'uk-slideshow-swipe-backward-in' : 'uk-slideshow-swipe-forward-in');
resolve();
}.bind(this));
},

备注

我只想补充一点,jQuery Promises(或他们称之为Deferred)在某个阶段有点崩溃,但这些天我认为它们符合Promise/A+规范。

许多jQuery函数(例如ajax、动画)都会返回promise,或者您可以返回.promise()——这就不需要我在答案中所做的事情,也就是使用promise构造函数反模式。

我对您的代码不太确定,不知道这些jQuery方法中是否有任何一个可以返回promise。

最新更新