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);
}
}
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)
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With