【发布时间】:2021-11-01 11:20:59
【问题描述】:
我正在使用 NextJS 和 MongoDB 构建一个 api。我在 API 文件的顶部进行了基本设置:
const { db } = await connectToDatabase();
const scheduled = db.collection('scheduled');
然后我用我的处理函数继续代码:
export default async function handler(req, res) {
otherFunctionCalls()
...
}
const otherFunctionCalls = async () => {
...
}
我知道 await 只能在异步函数中工作,但我想在处理程序调用的其他函数中使用 scheduled 常量,这就是我需要在顶部调用它的原因。
如果我将常量放在每个函数中,那就是代码重复。
访问scheduled 常量的最佳做法是什么?我应该在处理函数中添加otherFunctionCalls 声明吗?
我得到的完整错误:
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
File was processed with these loaders:
* ./node_modules/next/dist/build/babel/loader/index.js
You may need an additional loader to handle the result of these loaders.
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
【问题讨论】:
-
“我知道 await 只能在异步函数中工作......” 嗯,不,这就是顶级
await的重点——它在模块的顶层,在async函数之外。 -
正如错误消息告诉你的那样,如果你在工具中启用它给你那个错误,你只能使用顶级
await,因为它在任何工具中仍然是实验性的。信息。 (顶级await在 JavaScript 本身中是 not experimental anymore,但它很新,一些工具仍在迎头赶上。) -
@T.J.Crowder 我的错,谢谢提醒
-
@T.J.Crowder 是的,因此我想使用其他解决方案
-
你会更新这个问题吗?从这个问题我完全不明白。谢谢。 :-)
标签: javascript node.js reactjs next.js