# Async with getAccounts

I'm working on a simple project. Part of that requires retrieving accounts from the web3 provider asynchronously (so that they can be used as variables in the code of my frontend). My initial investigation suggested this should be simple enough - web3.eth.getAccounts() returns a promise, so you should simply be able to await it, and I in fact found examples of people doing just that online. However, when I tried that, it didn't work. I initially used a simple structure:

var currentAccount = await web3.eth.getAccounts()


I then tried putting it inside an async method:

  async function getCurrentAccount(){
currentAccount = await web3.eth.getAccounts();
console.log("getCurrentAccount has resolved, returning a value of " + currentAccount);
return currentAccount;
}


But running this with currentAccount = getCurrentAccount() simply produced the following error:

inpage.js:1 Uncaught TypeError: e is not a function
at inpage.js:1
at inpage.js:1
at inpage.js:1
at inpage.js:1
at i (inpage.js:1)
at inpage.js:1
at inpage.js:1
at u (inpage.js:1)
at s (inpage.js:1)
at inpage.js:1


I'm not sure what's causing this. Anyone got any advice?

Thanks

• What version of web3.js are you using? – smarx Jul 17 '18 at 22:50
• Sorry for the late response. Upon checking, it seems I'm running web3@1.0.0-beta.33 – Eoin Moloney Jul 19 '18 at 16:18
• Wouldn't you need currentAccount = await getCurrentAccount() because the function is async? In any case, I don't think this has anything to do with Ethereum... your issue is most likely about JavaScript and async/await. – smarx Jul 19 '18 at 16:21
• Yeah, that's probably right. I've actually managed to solve the issue thanks to someone else' help. Turns out I just needed to use web3.eth.getAccounts((err, accounts) => { currentAccount = accounts[0] } instead. – Eoin Moloney Jul 19 '18 at 17:50
• That's using a callback instead of a Promise. You should be able to do either. – smarx Jul 19 '18 at 17:54

I think this just has to do with the fact that web3 methods are error first.

As you said @eoin-moloney this works fine:

web3.eth.getAccounts((err, accounts) => { currentAccount = accounts[0] }


I find that the more I write JS the less convenient callbacks are, so what I do is wrap my web3 calls in a Promise. I'm not sure this is the most efficient way but it was the only way that I could get to work:

promisify = (fun, params=[]) => {
return new Promise((resolve, reject) => {
fun(...params, (err, data) => {
if (err !== null) reject(err);
else resolve(data);
});
});
}

getCurrentAccount = async () => {
const promise = promisify(web3.eth.getAccounts);
const accounts = await promise;
return accounts[0];
}


I think your problem is that web3.eth.getAccounts() returns an array

async function getCurrentAccount(){
const currentAccounts = await web3.eth.getAccounts();
console.log(getCurrentAccount has resolved, returning a value of \${currentAccounts[0]});
return currentAccounts[0];
}