Search code examples
node.jsasync-awaitioredis

Why async/await doesn't synchronizes ioredis get method execution inside a forEach loop?


Async/Await approach:

Ids = ['abc','lmn','xyz']

Ids.forEach(function (resId){
    console.log('inside loop');
    async function operation(){
        var curObj = await redisClient.get('key1');
        console.log('done waiting');
  }
}

Callback approach on another function:

function operation(cb) {
         redisClient.get('key1', cb);
       }
operation(function(){
    console.log('inside operation');
});

I wanted wait till the curObj variable sets and execute the code sequentially to print the 'done waiting'. I used async/await but it doesn't seem to work as expected. Then I used callback with the same get method still the same. I use ioredis library.

What have I done wrong?


Solution

  • Async/await approuch should look like this:

    (async() => {
      const Ids = ['abc','lmn','xyz'];
    
      const operation = async (){
       var curObj = await redisClient.get('key1');
       console.log('done waiting');
      }
    
    
      for (const resId of Ids){
       console.log('inside loop');
       await operation();
      }
    })()
    

    There is no async in forEach loop, but you can use it with for...of.
    Note, I'm using IIFE function just for example how to use async/await without other context.