1
for (var i = 0 ; i <= 4 ; i++) {
  myContract.methods.contractmanager(i).call().then((res) => {
    console.log(res[0]);
  }):
}

There are 2 data stored in my contract. I want to print it but it is not always 2, sometimes there will be more. It is dynamic and I wont know how many there will be.

After executing this code I have 2 output and 2 error. How do I make the loop stop at 2 so it wont show the errors? How do I detect the error and break the loop? How do I find out if the output is empty or not?

4
  • 1
    It is possible to do that in javascript using for await of inside a try {} catch {}.
    – Ismael
    Jul 15 '21 at 4:51
  • catch does not get the error
    – Meysam
    Jul 15 '21 at 20:28
  • 1
    Did you use await? Don't use promise.then().catch(), await and try/catch should work.
    – Ismael
    Jul 16 '21 at 5:00
  • what if you just have a returnAll function in the contract? Sep 3 '21 at 15:41
2
+50

You can use async/await.

(async function () {
    for await (let i of Array.from(Array(5).keys())) {
        let result= await  myContract.methods.contractmanager(i).call();
        console.log(result);
    }      
})();
1

If you want to break the loop when you detect an error then you should use async and await. For example:

const main = async () => {
  // ... the rest of your code before this

  for (let i = 0; i <= 4; i++) {
    try {
      const result = await myContract.methods.contractmanager(i).call()
      // handle the result
    } catch (err) {
      break // or handle the error however you'd like
    }
  }
}

main()
3
  • One problem is that javascript won't stop the loop at await and continue iterating while the call is pending.
    – Ismael
    Sep 3 '21 at 14:33
  • I don't believe that's true. Await will block if you're just using a standard for loop.
    – K. Fichter
    Sep 4 '21 at 19:07
  • My fault, you are correct. A promise doesn't stop the loop but the await stops the loop until the promise completes.
    – Ismael
    Sep 4 '21 at 20:01
1

You can check the output type using typeof method. Let's say the datatype of the two output is string:

(async () => {
     for(var i = 0 ; i <= 4 ; i++){
       const res = await myContract.methods.contractmanager(i).call();
         if(typeof res=="object" && typeof res[0]=="string" && && typeof res[1]=="string") {
            console.log(res[0], res[1]);
         } else break;
    }
})()
2
  • 1
    Similar problem that in KFichter answer, javascript won't stop the loop when the promise is called and continue iterating while the call is pending.
    – Ismael
    Sep 3 '21 at 14:34
  • @Ismael You are right. I have updated my answer. Sep 4 '21 at 6:51

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.