user

Shilpa

6 Mar 2022

Way to bypass a value if it is not existing in Async data fetch iterations

Node JS & Mongo

I wrote a script with node.js, which will invoke a function on a blockchain returning some output results. I have to collect the first 6k values (let's say 0 to 5.999K values).

let blockURIArr = [];
 for (let tknId= 0; tknId< 5999; tknId++) {
 let output = await BackendServices.tknBlockURI(tknId);
 console.log(output );
 blockURIArr .push(output );

 if (output = '') {
 continue;
 }
 }

Somehow, a few values do not exist and the loop is stopped when it encountered such issues. How should I prevent it?

Comments

Rakshit

6 Mar 2022

Best Answer

best answer

Why don't you use the “try-catch” block? It will fix your problem when iteration doesn't have any values.

Below code will be continued your loop throughout your condition used in for loop from stopping the iterations.

for (...) { // Add your for loop
 try{ // Add try block for your code
 let output = await BackendServices.tknBlockURI(tknId);
 	console.log(output);
 	blockURIArr.push(output);
 }catch(e){ //Handle exceptions when it throws exception.
 console.log(e); //Console iteration number which was failed. You can see the failed ones here.
 }
}

Also when you compare with IF CONDITION, please use `==` or  `===`, not the =

Your code contains =  for comparison, That's why it is assigning null value and fails from iterating throughout loops.

 if (output = '') {
 continue;
 }

Hope this will answer your question and help to fix your code fault.

Shilpa

6 Mar 2022

github

Thank you for putting my attention to if condition, I thought  - I put ==  only. This solution works!

© 2024 Copyrights reserved for web-brackets.com