Skip to main content
Fix spelling
Link
jfriend00
  • 711k
  • 104
  • 1.1k
  • 1k

Run a asynasync function within synchronously

Source Link
VinayGowda
  • 175
  • 3
  • 15

Run a asyn function within synchronously

I have a requirement to run an async function synchronously, I have tried the below approach. But the results are still async,

const asyncFunction = async () => { const count = await testSchema.countDocuments(); //Get total count from mongoDB console.log("COUNT ", count); return count; }; console.log("BEFORE ASYNC FUNCTION"); (async () => { await asyncFunction(); })(); console.log("AFTER ASYNC FUNCTION"); 

Output,

BEFORE ASYNC FUNCTION AFTER ASYNC FUNCTION COUNT 0