Ok, I'm new into JS and web3 and MetaMask. I'm still lost about Promise and async/await after reading them for 5 times!
I want to call my smart contract balanceOf method to check if there's enough balance of token before I execute a transfer.
How do I actually wait for this balanceOf value to return to my JS script then only I proceed?
You know, getting the balanceOf takes like only 1 sec, but I know sometimes the user's finger is faster than the brain.
I tried async/await function below but my main code doesn't "wait", it just continues on. I'm using web3 1.0.
Then, I execute the transfer in a separate function. What I'm doing now is firstly I set the token balance using setTokenBalance(balance). Then check if I have enough balance by calling getTokenBalance(). If yes, then I do the transfer. Which works but it's kinda funny cos there's a split second that getTokenBalance shows '0' since it hasn't got the correct balance data.
var tokenBalance = 0;
async function retrieveTokenBalance(contract, walletAddress) {
await contract.methods.balanceOf(walletAddress).call(function(err,res){
if(!err){
console.log(res);
setTokenBalance(res);
} else {
console.log(err);
}
});
}
function setTokenBalance(balance) {
tokenBalance = balance;
}
function getTokenBalance() {
return tokenBalance;
}
web3.js
rather thanweb3j
.