将 LocalForage 与 jQuery 的承诺库一起使用
Using LocalForage with jQuery's promise library
我使用 LocalForage 在浏览器中进行持久存储。我也(不幸地)在项目的其他地方使用 jQuery 的延迟和承诺。我正在尝试使用 $.when
来收集许多 LocalForage 请求的响应:
var results = _.map(keys, localForage.getItem);
$.when.apply($, results).then(function() {
// iterate over the arguments object
});
这...行不通。我已经验证 results
数组正确包含许多 ES6 promise 对象(或在某些浏览器中来自 LocalForage 内置 shim 的 shim promises)。这些对象上没有 .promise
函数,因此 $.when
不会将它们识别为承诺,并立即调用匿名函数 then
并将所有承诺作为参数。作为测试,我尝试将上面的代码更改为
var results = _.map(keys, _.constant($.Deferred().resolve(false)));
$.when.apply($, results).then(function() {
// iterate over the arguments object
});
并且它工作正常。
最好的解决办法是什么?有没有办法将 ES6/shim 承诺转换为 jQuery 承诺,而不是 var deferred = $.Deferred(); es6Promise.then(deferred.resolve, deferred.reject)
?
What is the best solution to this?
不要这样做。不要使用 $.when.apply
。不要将 ES6 承诺转换为 jQuery 延迟。
ES6 承诺在很多方面都优于 jQuery 延迟 - 最重要的是,它们遵循 Promises/A+ 并且可互操作,使同化不是问题。 你的情况应该是
var results = _.map(keys, localForage.getItem);
Promise.all(results).then(function(arr) {
// iterate over arr - no more arguments object!
});
我使用 LocalForage 在浏览器中进行持久存储。我也(不幸地)在项目的其他地方使用 jQuery 的延迟和承诺。我正在尝试使用 $.when
来收集许多 LocalForage 请求的响应:
var results = _.map(keys, localForage.getItem);
$.when.apply($, results).then(function() {
// iterate over the arguments object
});
这...行不通。我已经验证 results
数组正确包含许多 ES6 promise 对象(或在某些浏览器中来自 LocalForage 内置 shim 的 shim promises)。这些对象上没有 .promise
函数,因此 $.when
不会将它们识别为承诺,并立即调用匿名函数 then
并将所有承诺作为参数。作为测试,我尝试将上面的代码更改为
var results = _.map(keys, _.constant($.Deferred().resolve(false)));
$.when.apply($, results).then(function() {
// iterate over the arguments object
});
并且它工作正常。
最好的解决办法是什么?有没有办法将 ES6/shim 承诺转换为 jQuery 承诺,而不是 var deferred = $.Deferred(); es6Promise.then(deferred.resolve, deferred.reject)
?
What is the best solution to this?
不要这样做。不要使用 $.when.apply
。不要将 ES6 承诺转换为 jQuery 延迟。
ES6 承诺在很多方面都优于 jQuery 延迟 - 最重要的是,它们遵循 Promises/A+ 并且可互操作,使同化不是问题。
var results = _.map(keys, localForage.getItem);
Promise.all(results).then(function(arr) {
// iterate over arr - no more arguments object!
});