0

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
jfriend00
  • 683,504
  • 96
  • 985
  • 979
VinayGowda
  • 155
  • 2
  • 12
  • 8
    You cannot make an asynchronous function into a synchronous function. – Pointy Jul 14 '21 at 18:58
  • `async` functions do NOT block. They return a promise as soon as they hit an `await`. So, you can't fake an async function into a synchronous function. Can't be done in nodejs. You will need to learn how to program with asynchronous programming techniques. – jfriend00 Jul 14 '21 at 19:01
  • 1
    If you move `console.log("AFTER ASYNC FUNCTION");` up a line it would work. – crashmstr Jul 14 '21 at 19:03
  • 4
    *"I have a requirement to run an async function synchronously"*: no need to read further. This should never be your requirement. Embrace asynchrony: everything is possible with it. – trincot Jul 14 '21 at 19:04
  • 1
    `I have a requirement to run an async function synchronously` - something has been lost in translation. Either between the person who gave you the requirement and you, or you and SO. I would suggest you go back and clarify what the person who gave you the requirement actually wants (not just the "make async be sync", but what the "why" they want that) – Adam Jenkins Jul 14 '21 at 19:07
  • To avoid all the calling functions in the chain to me made async/await, I am trying this approach. – VinayGowda Jul 14 '21 at 19:12
  • 1
    @VinayGowda This approach does not (can not) work. [You have to deal with the asynchrony everywhere in your call chain](https://stackoverflow.com/a/35380604/1048572), there's no way around it. – Bergi Jul 14 '21 at 19:22

1 Answers1

2

You need to wrap everything in async. If you say...

async function main() {

  console.log("BEFORE ASYNC FUNCTION");

  await asyncFunction();

  console.log("AFTER ASYNC FUNCTION"); 

}
main();

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

main() returns a promise and is asynchronous... but we don't care.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135