Home > database >  How to incorporate continiously over a loop and querying of blockchain data in javascript
How to incorporate continiously over a loop and querying of blockchain data in javascript

Time:11-18

I'm new to javascript and am trying to query some blockchain data. I can query the data successfully when just querying once. But I would like to do this continuously.

When I use the while loop in an effort to continually run the query, it retrieves no data.

I've tried using a for loop with a range of 100, and see that it seems to wait until all 100 data points are found before returning.

I'm assuming it's doing something similar with my while loop and thus not returning anything because of its infinite nature. I've done this in python but seem to have issue with javascript.

My code is below.

const { LCDClient } = require('@terra-money/terra.js');

const terra = new LCDClient({
  //URL: 'https://bombay-lcd.terra.dev',
  //chainID: 'bombay-12',
  URL: 'https://lcd.terra.dev',
    chainID: 'columbus-5'
});


const contract = 'terra1a8k3jyv3wf6k3zngza5h6srrxcckdf7zv90p6u';
const pair_address = 'terra19l0hnypxzdrp76jdyc2tjd3yexwmhz3es4uwvz';
const query_msg = {"simulation": {"offer_asset": {"amount": "1", "info": {"token": {"contract_addr": contract}}}}}; 


while (true) {
    terra.wasm.contractQuery(pair_address, query_msg).then(result => {
    console.log(result);
    })
} 

CodePudding user response:

The javascript runtime is one thread , it has an event loop which is going to execute multiple queues in the below order:

  • call stack
  • macro tasks
  • micro tasks

when you are in an infinite while loop, the code execution will never *terminate the call stack execution & going to next step.

the execution of the promises listeners (thens) are in the micro tasks queue. so it would never reach there.

all this is because of the javascript runtime is single thread.

You should not use the while(true), loop, even on other languages, it will running infinity an busy one of your cpu cores

I recommend to use The setInterval() instead of while(true), if you want to polling a data source for changes.

setInterval( () => {
terra.wasm.contractQuery(pair_address, query_msg).then(result => {
    console.log(result);
    });
}, 5000);
    
  • Related