Last active
November 22, 2018 15:14
-
-
Save roadmanfong/8acfa9651d4e46aaa0d1 to your computer and use it in GitHub Desktop.
promiseWhile demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function promiseWhile(condition, body) { | |
var dfd = $.Deferred(); | |
function loop() { | |
if (!condition()) return dfd.resolve(); | |
body.apply(this, arguments) | |
.done(loop) | |
.fail(dfd.reject); | |
} | |
//call loop async | |
setTimeout(loop, 0); | |
// The promise | |
return dfd.promise(); | |
} | |
function sum(id, houses){ | |
var sumCandidate6 = 0; | |
var sumCandidate7 = 0; | |
var noDataHouseNum = 0; | |
for (var i = 0; i < houses.length; i++) { | |
var house = houses[i]; | |
sumCandidate6 += house.get('candidate6'); | |
sumCandidate7 += house.get('candidate7'); | |
if(house.get('candidate6') + house.get('candidate7') === 0){ | |
noDataHouseNum++; | |
} | |
} | |
return { | |
districtId: id, | |
candidate6: sumCandidate6, | |
candidate7: sumCandidate7, | |
noDataHouseNum: noDataHouseNum, | |
totalHouseNum: houses.length | |
}; | |
} | |
var districIdList = []; | |
//generate list | |
for(var index = 0 ; index < 12 ; index++){ | |
districIdList.push((6300100 + index*100).toString()); | |
} | |
//prepare result list | |
var districtVoteList =[]; | |
promiseWhile(function () { | |
return districIdList.length > 0; | |
}, function (results) { | |
var dfd = $.Deferred(); | |
var districtId = districIdList[0]; | |
if(results){ | |
console.log("districtId : " + districtId); | |
districtVoteList.push( | |
sum(districtId, results) | |
); | |
//remove first element | |
districIdList.shift(); | |
//select next query id | |
districtId = districIdList[0]; | |
} else { | |
console.log('---start promise while---') | |
} | |
//fake query find callback | |
setTimeout(function(){ | |
function House(attrs){ | |
this.attrs = attrs; | |
this.get = function(name) { | |
return this.attrs[name]; | |
} | |
} | |
dfd.resolve([ | |
new House({ | |
candidate6: 1, | |
candidate7: 2 | |
}), | |
new House({ | |
candidate6: 1, | |
candidate7: 2 | |
}), | |
new House({ | |
candidate6: 0, | |
candidate7: 0 | |
}), | |
]); | |
}, 10); | |
// query.equalTo("districtId", districtId); | |
// return query.find(); | |
return dfd.promise(); | |
}) | |
.done(function() { | |
console.log('all done'); | |
console.log(districtVoteList); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment