Zugriff auf die Ethereum-Statusvariablen mit web3js (Java Script)

Ich versuche, den folgenden Code auszuführen, um die Statusvariablen mithilfe der getIdBytes-Methode des Smart Contract abzurufen und sie einer Java-Skript-Array-Variablen zuzuweisen, aber es scheint nicht zu funktionieren.

Ich kann nur die zurückgegebenen Werte mit console.log(return) drucken.

Kann mich bitte jemand in die richtige Richtung weisen?

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]);

So sieht die Ausgabe aus.

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

Sollte ich Ereignisse verwenden ?

Antworten (1)

Die Ausführung des web3js-Aufrufs ist asynchron, sodass „After Call“ vor dem Code innerhalb der Schleife ausgeführt wird.

Versuche dies:

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]);

Eine andere Möglichkeit ist die Verwendung von "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...