我将以下JavaScript代码从库中删除,并使用与官方Promise规范不同的jQuerys Deferred / promises。
我很感激任何帮助,只需将此基本示例转换为原生JavaScript承诺,同时保持相同的格式/结构。
我在网上找到的几乎每个示例Promise用法都是异步加载某些东西我有一些情况我想将它们用于其他任务,这个例子就是这样!
App.show()
被称为App.show()
调用一个返回Promise
App.Animations.swipe.apply(this, [current, next, dir]).then(finalize);
finalize
函数内的App.show()
函数。通过简单地查看下面的示例,可能更容易理解它的作用....
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();
},
}
};
那么基于该代码如何将其转换为不使用jQuerys Deferred并使用Native JS Promises?
答案 0 :(得分:1)
'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(或Deferreds,因为他们称之为)在一个阶段被打破,但这些天我认为他们符合Promise / A +规范。
许多jQuery函数(例如ajax,动画)都会返回一个promise,或者你可以返回
.promise()
- 这就无法回答我在答案中所做的事情,那就是使用一个promise构造函数反模式。我不确定您的代码是否知道这些jQuery方法是否可以返回承诺