user image

Shilpa
Published in : 2022-03-06

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 Date : 2022-03-06

Best answers

34

Best answers

34

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 Date : 2022-03-06

Best answers

10

Best answers

10

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

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

[Solved] SyntaxError: Unexpected token o in JSON at position 1 NodeJS
Publish date: 2021-06-13 | Comments: 1

Tag: Node JS & Mongo