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
7
  • 8
    You cannot make an asynchronous function into a synchronous function. Commented Jul 14, 2021 at 18:58
  • 1
    If you move console.log("AFTER ASYNC FUNCTION"); up a line it would work. Commented Jul 14, 2021 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. Commented Jul 14, 2021 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) Commented Jul 14, 2021 at 19:07
  • 1
    @VinayGowda This approach does not (can not) work. You have to deal with the asynchrony everywhere in your call chain, there's no way around it. Commented Jul 14, 2021 at 19:22

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.