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?

3
  • There is an appropriate solution code here.
    – Alireza
    Apr 12, 2020 at 11:48
  • There is an appropriate solution code here
    – Alireza
    Apr 12, 2020 at 11:50
  • You should make a Jade file in first. After that, you determine a field in the Jade file so that it accepts the given value. After that, you can see the value in browser based on code you embedded in Jade. Take a look at: https://www.tutorialsteacher.com/nodejs/jade-template-engine
    – Kia0122
    May 17, 2021 at 8:58

2 Answers 2

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.

2
  • 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, 2020 at 9: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??? Feb 10, 2020 at 9: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.