问题在于 JavaScript 的异步特性,应用程序在删除旧的之前没有等待区块链的响应,所以发生的情况是数据被插入到 dom 中两次,解决方法是以不同的方式处理 Promise。将所有的 Promise 调用分组以将候选人放入一个数组,然后等到所有这些都被解决后再将它们添加到 dom 中。
App.contracts.Election.deployed()
.then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
})
.then(function(candidatesCount) {
const promises = [];
// Store all prosed to get candidate info
for (var i = 1; i <= candidatesCount; i++) {
promises.push(electionInstance.candidates(i));
}
// Once all candidates are received, add to dom
Promise.all(promises).then(candidates => {
var candidatesResults = $("#candidatesResults");
candidatesResults.empty();
var candidatesSelect = $("#candidatesSelect");
candidatesSelect.empty();
candidates.forEach(candidate => {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate =
"<tr><th>" +
id +
"</th><td>" +
name +
"</td><td>" +
voteCount +
"</td></tr>";
candidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption =
"<option value='" + id + "' >" + name + "</ option>";
candidatesSelect.append(candidateOption);
});
});
return electionInstance.voters(App.account);
})