Loading...
Using synchronous calls is both a technical limitation and a user experience issue . They block use's interface .
For better development and to provide enhanced user experience , we need to make web3 calls asynchronous .
You can make an asynchronous requests by adding an error first callback to the Web3.js functions .
web3.eth.getBalance(address, function (error, result) {
if (!error) {
console.log(result);
} else {
console.error(error);
}
});
If we depend on multiple calls from the Ethereum blockchain to create a result , using JavaScript Promises is a good solution . They allow you to react to a success or a failure from an asynchronous function.
function getBalance (address) {
return new Promise (function (resolve, reject) {
web3.eth.getBalance(address, function (error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
})
}
We can make this process simpler by creating a wrapper which makes the function asynchronous and turn it into a promise .const promisify = (inner) => new Promise((resolve, reject) => inner((err, res) => { if (err) { reject(err); } else { resolve(res); } }) );
We can now make use of async/await pattern for simpler approach .
async function getBalance() { var address, wei, balance address = document.getElementById("address").value; wei = promisify(cb => web3.eth.getBalance(address, cb)) try { balance = web3.fromWei(await wei, 'ether') document.getElementById("output").innerHTML = balance + " ETH"; } catch (error) { document.getElementById("output").innerHTML = error; } }