gpt4 book ai didi

javascript - 将 LocalForage 与 jQuery 的 Promise 库结合使用

转载 作者:行者123 更新时间:2023-12-02 15:47:02 24 4
gpt4 key购买 nike

我使用 LocalForage 在浏览器中进行持久存储。我还在项目的其他地方(不幸的是)使用了 jQuery 的 deferreds 和 Promise。我正在尝试使用 $.when 收集来自许多 LocalForage 请求的响应:

var results = _.map(keys, localForage.getItem);
$.when.apply($, results).then(function() {
// iterate over the arguments object
});

这...行不通。我已经验证 results 数组正确包含许多 ES6 Promise 对象(或在某些浏览器中来自 LocalForage 内置 shim 的 shim Promise)。这些对象没有 .promise 函数,因此 $.when 不会将它们识别为 Promise,并调用匿名 then 以所有 Promise 作为参数立即运行。作为测试,我尝试将上面的代码更改为

var results = _.map(keys, _.constant($.Deferred().resolve(false)));
$.when.apply($, results).then(function() {
// iterate over the arguments object
});

并且它工作正常。

对此最好的解决方案是什么?除了 var deferred = $.Deferred(); 之外,还有其他方法可以将 ES6/shim promise 转换为 jQuery promise 吗? es6Promise.then(deferred.resolve, deferred.reject)?

最佳答案

What is the best solution to this?

别这么做。不要使用$.when.apply。不要将 ES6 Promise 转换为 jQuery Deferreds。

ES6 Promises 在很多方面都比 jQuery deferreds 更好 - 最重要的是,它们遵循 Promises/A+ 并且具有互操作性,使得同化不再是问题。 You can easily use them with jQuery.在你的情况下,它应该是

var results = _.map(keys, localForage.getItem);
Promise.all(results).then(function(arr) {
// iterate over arr - no more arguments object!
});

关于javascript - 将 LocalForage 与 jQuery 的 Promise 库结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32125587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com