在同步内运行异步函数

时间:2021-07-14 18:55:53

标签: javascript node.js asynchronous async-await promise

我需要同步运行异步函数,我尝试了以下方法。但是结果还是异步的,

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"); 

输出,

BEFORE ASYNC FUNCTION
AFTER ASYNC FUNCTION
COUNT  0

1 个答案:

答案 0 :(得分:1)

您需要将 一切 包裹在 async 中。如果你说...

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() 返回一个 promise 并且是异步的......但我们不在乎。