【问题标题】:Run a async function within synchronously同步运行异步函数
【发布时间】:2021-09-23 18:22:45
【问题描述】:

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

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

【问题讨论】:

  • 不能将异步函数变成同步函数。
  • 如果您将console.log("AFTER ASYNC FUNCTION"); 向上移动一行,它会起作用。
  • “我需要同步运行一个异步函数”:无需进一步阅读。这绝不应该是您的要求。拥抱异步:一切皆有可能。
  • I have a requirement to run an async function synchronously - 翻译中丢失了一些东西。要么在给你要求的人和你之间,要么在你和 SO 之间。我建议你回去澄清一下给你要求的人真正想要什么(不仅仅是“使异步同步”,而是他们想要的“为什么”)
  • @VinayGowda 这种方法不起作用(不能)。 You have to deal with the asynchrony everywhere in your call chain,没办法。

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


【解决方案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() 返回一个承诺并且是异步的......但我们不在乎。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多