我试图getItem
从 LocalForage 库中链接多个承诺,键是从数组中读取的。
问题: 在所有 LocalForage 承诺完成后,我需要 Resolve 或 Reject 回调来触发。
两种方法都没有正确的调用堆栈。有任何想法吗?
代码 1:
function load(keyHandlerPairs, correct, incorrect) {
var result = {
resolved: 0,
rejects: 0,
},
p = new Promise(function (resolve, reject) {
//Retrieve objects from localstorage;
if ($.isArray(keyHandlerPairs)) {
for (var i = 0; i < keyHandlerPairs.length; i++) {
var kv = keyHandlerPairs[i];
lf.getItem(kv.key, kv.handler).then(
//Resolved
function () { console.log('resolved'); result.resolved++; }
);
}
} else {
var kv = keyHandlerPairs;
lf.getItem(kv.key, kv.handler);
}
if ((result.resolved + result.rejects) == keyHandlerPairs.length) {
console.log(result.resolved, result.rejects, keyHandlerPairs.length);
resolve(result);
} else {
console.log(result.resolved, result.rejects, keyHandlerPairs.length);
reject(result);
}
}).then(correct, incorrect);
}
代码替代:
if ($.isArray(keyHandlerPairs)) {
var promises = [];
for (var i = 0; i < keyHandlerPairs.length; i++) {
var kv = keyHandlerPairs[i];
promises.push(lf.getItem(kv.key, kv.handler));
}
Promise
.all(promises)
.then(function (value) { console.log(value); result.resolved++; })
.catch(function (error) { console.log(error); result.rejects++; });
} else {
var kv = keyHandlerPairs;
lf.getItem(kv.key, kv.handler);
}