You can install a block filter and only update balances when a new block arrives.
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const address = "0x9b....";
let balance = web3.eth.getBalance(address);
const filter = web3.eth.filter('latest');
filter.watch((err, res) => {
if (err) {
console.log(`Watch error: ${err}`);
} else {
// Update balance
web3.eth.getBalance(address, (err, bal) => {
if (err) {
console.log(`getBalance error: ${err}`);
} else {
balance = bal;
console.log(`Balance [${address}]: ${web3.fromWei(balance, "ether")}`);
}
});
}
});
The async/await patern works with JavaScript Promises.
In order to make web3.js functions asynchronous, you need to pass a callback parameter:
As this API is designed to work with a local RPC node, all its
functions use synchronous HTTP requests by default.
If you want to make an asynchronous request, you can pass an optional
callback as the last parameter to most functions. All callbacks are
using an error first callback style:
web3.eth.getBlock(48, function(error, result){
if(!error)
console.log(JSON.stringify(result));
else
console.error(error);
})
If you want to then make this work with the async/await pattern, you will need to then wrap this asynchronous function into a promise, which is of the format:
new Promise( /* executor */ function(resolve, reject) { ... } );
Rather than do this over an over for each web3.js function, you can automate this process by creating a wrapper for javascript functions which includes the callback parameter and wraps it in a promise as so:
const promisify = (inner) =>
new Promise((resolve, reject) =>
inner((err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
})
);
This can then be used really simply with nearly all existing web3.js functions:
async function getBalance() {
var address, wei, balance
address = document.getElementById("address").value;
wei = promisify(cb => web3.eth.getBalance(address, cb)) // simply wrap web3.js functions with the promisify function, also passing in a callback parameter
try {
balance = web3.fromWei(await wei, 'ether')
document.getElementById("output").innerHTML = balance + " ETH";
} catch (error) {
document.getElementById("output").innerHTML = error;
}
}
All of this information can be found on my blog where you can also find other small projects I have done which use this pattern.
Best Answer
Hi bro you just need to set the web3 from your react app and dont use metamask web3 . You just need to do this way : const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/INFURA_ACCESS_TOKEN:8545')) *You need to create an infuria account and add your infuria sting here , after that you will have web3 that work so you could use your function const balance = await web3.eth.getBalance( "0xu28yjy9chxmhiruhgiwgm93h984hmxhumzmr" );
Take a look here :) How to use infura API with web3 js?