我目前正在使用Javascript,Async / Await和Web3(以太坊)的项目中工作。我希望创建一个能够检测用户的Metamask地址,然后在函数中使用该地址的前端页面。我已经在上一页中获得了类似的功能,但是在将其转换到另一页时遇到了麻烦。我怀疑getCurrentAccount()不会返回任何东西,从而弄乱了Promise.all期望发送的变量的数量和类型。相关代码为:
function isInList(input) {
return new Promise(function(resolve, reject) {
myElection.areYouInList(input, function(error, response) {
if (error) {
reject(error);
} else {
resolve(response);
}
})
});
}
function hasntVotedYet(input) {
return new Promise(function(resolve, reject) {
myElection.haveYouVotedAlready(input, function(error, response) {
if (error) {
reject(error);
} else {
resolve(response);
}
})
});
}
function isNotOver() {
return new Promise(function(resolve, reject) {
myElection.isItOver(function(error, response) {
if (error) {
reject(error)
} else {
resolve(response);
}
})
});
}
async function getCurrentAccount() {
console.log("getCurrentAccount method");
web3.eth.getAccounts((err, accounts) => {
currentAccount = accounts[0]
})
return currentAccount; //KEEP IN MIND THAT YOU NEED TO ACTUALLY BE LOGGED INTO METAMASK FOR THIS TO WORK - OTHERWISE IT'LL RETURN UNDEFINED BECAUSE THERE AREN'T ANY ACCOUNTS
}
async function verify() {
console.log("Verify");
try {
-- -- > THIS LINE //
var myCurrentAccount = await getCurrentAccount();
console.log("myCurrentAccount is: " + myCurrentAccount);
data = await Promise.all([isInList(myCurrentAccount), hasntVotedYet(myCurrentAccount), isNotOver()]); //data then equals an array, containing both the strings returned from these two methods
console.log("success");
console.log(data)
if (data[0] && !data[1] && !data[2]) { //check firstly that we are allowed to vote, secondly that we have not already voted, and finally that this vote is not over yet
var x = document.getElementById("hidden");
x.style.display = "block";
} else if (!data[0]) {
alert("That address was not found in the Whitelist.");
} else if (data[1]) {
alert("You have already voted and may not vote a second time");
} else if (data[2]) {
alert("This election has already concluded. Votes can no longer validly be cast for it.");
}
} catch (error) {
console.log("Promise.all finished with error " + error)
}
}
答案 0 :(得分:0)
问题出在获取元掩码帐户的方式上:web3.eth.getAccounts
是一个异步函数。这样的事情应该起作用:
async function getCurrentAccount() {
console.log("getCurrentAccount method");
let accounts = await web3.eth.getAccounts();
return accounts[0];
}