我試圖從LocalForage庫鏈接多個getItem
承諾,這些密鑰是從數組中讀取的。來自LocalForage for JavaScript循環的JavaScript鏈接承諾
問題: 我需要Resolve或Reject回調觸發所有LocalForage承諾完成後。
這兩種方法都沒有正確的調用堆棧。有任何想法嗎?
CODE 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);
}
CODE ALT:
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);
}
你是否真的試圖連續鏈接它們,還是並行執行它們? – Bergi 2014-09-30 18:36:04
我假設你使用Mozilla的ES6'Promise'? – Bergi 2014-09-30 18:37:52
是的,我想讓它們平行鏈接。我希望當這些承諾中的每一個都完成時履行承諾。 – 2014-09-30 20:21:37