Pawan Kumar
Pawan Kumar

Reputation: 522

Await inside Foreach Giving Error in TypeScript

I was having a JS develop in Express JS and we are migrating the application to Typescript for TypeOrm.

async function loadRootMessagesForTwitter(req, res) 
{
 const messageRepository = getManager().getRepository(Message);
 req.body.forEach(function(obj) {
  const requestMessage = messageRepository.create(obj);
    var channel_message_ID = requestMessage['channel_message_ID'];
    if (channel_message_ID) {                      
           await messageRepository.save(requestMessage);
        }
     }

And i am facing the below Error

error TS1308: 'await' expression is only allowed within an async function

Upvotes: 1

Views: 1102

Answers (3)

Duncan
Duncan

Reputation: 95742

Simply using forEach with an async callback doesn't work if you want to ensure you wait for each save() call to complete before doing the next iteration of the loop. That may not matter in this case as you're ignoring any result of the save() call, perhaps you can just throw out a bunch of calls to save() and in that case simply:

 const messageRepository = getManager().getRepository(Message);
 req.body.forEach(function(obj) {
  const requestMessage = messageRepository.create(obj);
    var channel_message_ID = requestMessage['channel_message_ID'];
    if (channel_message_ID) {                      
           messageRepository.save(requestMessage);
        }
     }

However, if you want to control the calls then just stop using forEach and use typescript's for...of instead:

 const messageRepository = getManager().getRepository(Message);
 for (let obj of req.body) {
  const requestMessage = messageRepository.create(obj);
    var channel_message_ID = requestMessage['channel_message_ID'];
    if (channel_message_ID) {                      
           await messageRepository.save(requestMessage);
    }
  }
 }

Upvotes: 0

tony19
tony19

Reputation: 138696

The function passed to forEach would have to be async:

req.body.forEach(async function(obj) {
  // ...
  await messageRepository.save(requestMessage);
});

Upvotes: 2

mehulmpt
mehulmpt

Reputation: 16597

Why not do this?

async function loadRootMessagesForTwitter(req, res) {
 const messageRepository = getManager().getRepository(Message);
 const arr = req.body;
 for(let i=0;i<arr.length;i++) {
  let obj = arr[i]
  const requestMessage = messageRepository.create(obj);
  let channel_message_ID = requestMessage['channel_message_ID'];
  if (channel_message_ID) {                      
    await messageRepository.save(requestMessage);
  }
 }
}

Upvotes: 0

Related Questions