NodeJS do function after loop with promise

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…

Answer

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.
})