0

I have a server that sometimes can go offline and miss some open data to add in database. So I'm making a function to reach this events after going back online. Every events MUST be write ONE after ONE. Then it can listen to new one. Currently, I did do a "for loop" with promise inside that can

const someProcedure = async events => {
     for (let i = 0; i < events.length; i++) {
         const x = await new Promise(r => {
             web3.eth.getBlock(events[i].blockNumber).then(result => { 
                   console.log(convertEvent(events[i], result.timestamp)); })
                   .then(r());
          })
      }
                                    
}

someProcedure(events).then(function(result) {
console.log('Loop finished, do...');
//If I add a function here, does it need to be a promise ?                                    
})

"Console.log" inside my loop works great but not the last "loop finished...".

I did implement some example from here...

GrindCode
  • 179
  • 2
  • 9
  • Could you explain what you mean by -> works great but not the last "loop finished...". – Keith Apr 07 '21 at 14:22
  • In my console log I have : `Loop finished, do... convertedEvents1 convertedEvents2 convertedEvents3` But I want : `convertedEvents1 convertedEvents2 convertedEvents3 Loop finished, do...` – GrindCode Apr 07 '21 at 14:23
  • @GrindCode you must use rabbitmq here so that even your server goes offline no data will be missed to insert in the db. By using that whenever your server comes back online it will consume data and insert that in db. – Priyanka Giri Apr 07 '21 at 14:38

1 Answers1

1

Not sure why 'Loop finished, do...' does not get logged.

But maybe we could first try tidying up your code. Firstly you have a Promise Constructor for a Promise, and your mixing thenables with async / await..

So after doing this your code could look like.

const someProcedure = async events => {
  for (let i = 0; i < events.length; i++) {
    const result = await web3.eth.getBlock(events[i].blockNumber);
    console.log(convertEvent(events[i], result.timestamp));
  }                                   
}

someProcedure(events).then(function() {
  console.log('Loop finished, do...');
  //If I add a function here, does it need to be a promise ?
  //^^ No, unless the function is async, but if it is
  //it would make sense to return another promise, and probably
  //use async / await again to keep things tidy.
})
Keith
  • 22,005
  • 2
  • 27
  • 44