【发布时间】:2017-01-12 08:25:57
【问题描述】:
我从库中提取了下面这段 JavaScript 代码,它使用了与官方 Promise 规范不同的 jQuerys Deferred/promises。
如果能简单地将这个基本示例转换为原生 JavaScript Promise,同时保持以下相同的格式/结构,我将不胜感激。
我在网上找到的几乎每个 Promise 用法示例都是异步加载某些内容,我在某些情况下想将它们用于其他任务,而这个示例就是这样做的!
-
App.show()被调用 -
App.show()调用返回PromiseApp.Animations.swipe.apply(this, [current, next, dir]).then(finalize);的函数 - promise 函数内部有一个事件处理函数,当 CSS 动画完成并触发 Promise 解析时运行。
- 当 Promise 解决后,它会调用
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?
【问题讨论】:
-
不推荐您在这里要求的内容。 Native Promises 会同化 jQuery Promises,但 jQuery Promises 不会同化原生 Promises。因此,在 jQuery 环境中,低级别的承诺(例如
.swipe())应该返回一个 jQuery 承诺,以确保它被 jQuery 承诺链或调用堆栈中更高的jQuery.when()同化。只要.show()(目前写的)是唯一的调用者,你就可以返回一个原生承诺。但是,如果在其他地方调用.swipe(),您可能会遇到麻烦。
标签: javascript jquery promise jquery-deferred