0

There are 10 Ethereum accounts in Ganache. I work on a Truffle project. Whenever i run the following codes in Nodejs:

var Web3 = require('web3');
var web3 = new Web3("ws://localhost:8545");
var acc= Promise.resolve(web3.eth.getAccounts());
acc.then(function(ins){console.log(ins[0]);});

Address of the first account will be shown:

enter image description here

But i want to see that address in my browser. What is the appropriate code?

Alireza
  • 533
  • 5
  • 15

2 Answers2

1

In your working example, you are handling the result of getAccounts in an asynchronous manner:

web3.eth.getAccounts().then(console.log);

In your non-working example, you are wrongfully assuming that it runs synchronously to completion:

var acc=web3.eth.getAccounts();

Function web3.eth.getAccounts returns a Promise object which, when resolved, contains all the accounts which are unlocked on the node that your web3 object is connected to.

Resolve this promise, and you should be good.

goodvibration
  • 26,003
  • 5
  • 46
  • 86
  • I am a beginner in programming and my knowledge about promise and JavaScript is low. Please clear more about resolve the promise. – Alireza Feb 10 '20 at 09:31
  • @A.Kiakojouri: How hard is it, even for a beginner, to take a working example (which you already have!!!) and use it instead of the non-working example??? – goodvibration Feb 10 '20 at 09:43
1

To see a contract's values in browser with web3, you should create some .jade file. For interacting with a smart contract from a browser, the workflow is this: There are 3 levels: 1) Blockchain level, 2) Nodejs level, and 3) UI/browser level. In "blockchain level" there is the given smart contract (that you have it). In "Nodejs level" there is the related JavaScript code that requires web3 module and uses its methods. In "UI/browser level" there is your browser. The contract connects to Nodejs with web3 and they send their data together. On the other hand ,Nodejs and browser send their data together, too. To see this sent data in the browser you should create some .jade file. Nodejs sends its data to that .jade file and you execute that file via your browser. In order to do this successfully, you need to know JavaScript programming in Nodejs.

Kiasha
  • 131
  • 6