我最近下载了一个使用 ES6 Promises 的库。由于我想部署到不支持 Promises 的浏览器,我还下载了 polyfill .
既然我已经包含了 jQuery,我就考虑为 Promise 编写一个 polyfill,它在内部使用 jQuery 的 Deferred。
我编写了这个简单的polyfill,足以满足我的特定用例:
window.Promise = function(cb){
var promise = $.Deferred();
cb(promise.resolve, promise.reject);
return promise.promise();
};
这样做的问题是它没有涵盖整个规范(就像缺少 Promise.all()
一样)。
在我投入大量时间之前,我想知道是否可以使用 jQuery 的 Deferred 为 Promise 编写完整的 polyfill。还是有一些功能是无法复制的?
最佳答案
things like
Promise.all()
are missing
Promise.all
或多或少可以被 using $.when
复制。 Promise.race
可以通过创建一个延迟对象来复制,该延迟对象的 resolve
/reject
方法附加到所有输入 promise 。
The problem with this is that it doesn't cover the whole specification
没有。未涵盖的部分可以轻松添加。真正的问题是 jQuery Deferred
实现的现有部分不符合规范 - 请参阅 Problems inherent to jQuery $.Deferred (jQuery 1.x/2.x)
Before I invest a lot of time into this I'd like to know if it is possible to write a full polyfill for Promise using jQuery's Deferred. Or are there some features which can't be replicated?
一切都可以复制,但是您需要在Deferred
实现中进行足够的monkeypatch,这样您最好只使用现有的polyfills之一。如果您确实想创建自己的,您可以将其基于 jQuery.Callbacks("once memory")
.
关于jquery - 基于 jQuery Deferred 的 ES6 Promise polyfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25592722/