Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling an async function inside for loop in JavaScript / node js

I want to call an async function inside for loop

function test(req,res){
 //somelogic part here
 
 async function create(data){
 //logic part here
 }
 
 for( var value in values){
  // some codeing part here
  await create(data);
  }
}
I am getting this error
uncaughtException: await is only valid in async function 

then I can't call an async function inside For loop. I know it is written like this but is there any possible way I can call an async function inside for loop

for await (var value in values)

2 Answers

Hi As I understood your concern I would suggest to use .map() function which is very useful in this type of case.

async function create(data) {
   // Create user logic here
}
const usernames = ['test1', 'test2', 'test3'];
const createdUsers = usernames.map(async (val) => {
    const user = await create();
    return user;
});

await Promise.all(createdUsers);
like image 104
Ashish Sharma Avatar answered May 01 '26 23:05

Ashish Sharma


Just put async in front of function test.

async function test(req, res) {…

If you want to await a promise, then the function that's using await needs to be async function.

like image 28
Ethan Doh Avatar answered May 01 '26 22:05

Ethan Doh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!