1

I'm trying to run the below code to get the state variables using the getIdBytes method of the Smart Contract, and assign it to a java script array variable, but it doesn't seem to work.

All I can do is print the returned values using console.log(return).

Can someone point me in the right direction please?

var coreValues = ['Apple', 'Banana'];
console.log("Before call :"  + coreValues[1]);

if (get_flag)
{
contract3.methods.getIdBytes(index1, abstract_contract_address).call().then(function(result){
   for (var i = 0; i < 5; i++) {
  coreValues[i] =  result[i];
  console.log("Inside Function Call" + coreValues[i]);
  }
});

console.log("After Call :" + coreValues[0]);

Here's what the output looks like.

Before call :Banana
After Call :Apple
Inside Function call : Steve
Inside Function call : Rogers
Inside Function call : Male
Inside Function call : 0987654
Inside Function call : 12/05/1980

Should I be using events?

0

Execution of the web3js call is asynchronous, so "After Call" is executed before the code inside the loop.

Try this:

var coreValues = ['Apple', 'Banana'];
console.log("Before call :"  + coreValues[1]);

if (get_flag) {
  contract3.methods.getIdBytes(index1, abstract_contract_address).call().then(function(result){
    for (var i = 0; i < 5; i++) {
      coreValues[i] =  result[i];
      console.log("Inside Function Call" + coreValues[i]);
    }
    console.log("End of Call :" + coreValues[0]);
    // continue with your logic here...
  });
}
console.log("Too early: " + coreValues[0]);

Another option is to use "await":

var coreValues = ['Apple', 'Banana'];
console.log("Before call :"  + coreValues[1]);

if (get_flag) {
  await contract3.methods.getIdBytes(index1, abstract_contract_address).call().then(function(result){
    for (var i = 0; i < 5; i++) {
      coreValues[i] =  result[i];
      console.log("Inside Function Call" + coreValues[i]);
    }
  });
}
console.log("Not too early: " + coreValues[0]);
// continue with your logic here...

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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