-2

I've followed and completed this tutorial https://github.com/dappuniversity/election/tree/2019_update. However, duplicate rows show up at the end when I'm adding new votes in (shown in picture).

Candidate 1 and Candidate 2

I'm not familiar with dApps, web development, or javascript so I don't know where my error is.

Code from https://github.com/dappuniversity/election/tree/2019_update.

I don't know where adding the new rows came in and I'm trying to prevent it.

4

1 回答 1

0

问题在于 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);
  })
于 2019-06-26T15:54:09.563 回答