[Ethereum] Get return value from solidity function

solidityweb3js

This may be javascript question, but I am totally out of ideas.

I have a function in solidity code returning a variable:

  function getIdentifier() public view returns (string) {
    return identifier;
  }

I want to simply call this function with web3.js and store result as a variable. But all I can do is console.log the result (I know, I know =/).

Following code console.logs the variable:

contractInstance.methods.getIdentifier().call().then(console.log);

Works fine, but I simply want to store the return of getIdentifier() in a variable x.

None of the following naive code work:

x = contractInstance.methods.getIdentifier();
x = contractInstance.methods.getIdentifier().call();

I am sorry for a dumb question, but I have tried tons of things and it still does not work.

EDIT:
Thanks smarx your code works, but I still would like to keep the variable for later use. Strangely something like this does not work:

var y = "";
contractInstance.methods.getIdentifier().call()
.then(function (x) {
  y = x;
});
console.log(y) // still empty!!! :(

Best Answer

This is just a JavaScript question. :-)

contractInstance.methods.getIdentifier()
.then(function (x) {
  // Use x in here.
});

// This code runs BEFORE the callback, and x won't be defined out here.
Related Topic