0

I want to determine a view function of a smart contract result in web3js 1.x

Suppose we have a view function getName(uint code) and want to get the name of a person having his code. So we write:

contract.methods.getName(code).call(option)
  .then(...)
  .catch(...);

We want to define a function to return the result name and do something with it.

How can we relate the defined function and method call?

For example:

async function name(code) {
  contract.methods.getName(code).call(option)
    .then(...)
    .catch(...);
  return ???
}

for (let i = 0; i <= 10; i++) {
  let x = name(i);
  // Do something with x, for example:
  alert(x); 
}
  • just learn about promises, the return result is in .then((result) => {}) – rstormsf Nov 2 '19 at 18:16
  • I know that the result is accessible in .then but I need the result to be returned from name function. How can I access it inside the name function? @rstormsf – Alireza Zojaji Nov 2 '19 at 18:20
3

You declared you function as async, but you didn't make use of the async/await pattern.

async function name(code) {
  return await contract.methods.getName(code).call(option);
}

You don't need to use .then. I am not quite sure but the return value is some sort of JSON object with more data than you actually need. I think you can manage on you own which properties you want.

  • This solution in not usable in the for loop given in the question (an await is required in each iteration, and the entire loop needs to be placed in an async function). – goodvibration Nov 2 '19 at 20:09

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.