我有以下想要重构的功能,并且正在寻找可以用来使其更加精简的任何提示/技巧。
function resolveNotifyPromises(type, elem) {
if (elem && elem.id) {
if (promises[type] && promises[type][elem.id] && promises[type][elem.id].defereds) {
for (var i = 0; i < promises[type][elem.id].defereds.length; i++) {
promises[type][elem.id].defereds[i].resolve(elem);
promises[type][elem.id].defereds.pop(promises[type][elem.id].defereds[i]);
}
}
} else if (type) {
if (promises[type] && promises[type].defereds) {
for (var i = 0; i < promises[type].defereds.length; i++) {
promises[type].defereds[i].resolve(type);
promises[type].defereds.pop(promises[type].defereds[i]);
}
}
} else {
if (promises.defereds) {
for (var i = 0; i < promises.defereds.length; i++) {
promises.defereds[i].resolve("all");
promises.defereds.pop(promises.defereds[i]);
}
}
}
}
function checkRefCountsAndNotify(type, elem) {
var propCount = 0;
if (type && elem) {
resolveNotifyPromises(type, elem);
refCounts[type][elem.id] = 0;
}
if (type) {
for (var prop in refCounts[type]) {
if (refCounts[type][prop] === 1) propCount++;
}
if (propCount === 0) resolveNotifyPromises(type);
}
if (propCount === 0) {
for (var prop in refCounts) {
for (var prop2 in refCounts[prop]) {
if (refCounts[prop][prop2] === 1) propCount++;
}
}
if (propCount === 0) resolveNotifyPromises();
}
}
notifyOnComplete: function (type, elem) {
promises.defereds = promises.defereds || [];
if (type) {
promises[type] = promises[type] || {};
promises[type].defereds = promises[type].defereds || [];
}
if (elem && elem.id) {
promises[type][elem.id] = promises[type][elem.id] || {};
promises[type][elem.id].defereds = promises[type][elem.id].defereds || [];
}
var defered = $q.defer();
if (elem && elem.id) {
promises[type][elem.id].defereds.push(defered);
} else if (type) {
promises[type].defereds.push(defered);
} else {
promises.defereds.push(defered);
}
checkRefCountsAndNotify();
return defered.promise;
}