【问题标题】:top-level-await error when using NextJS API使用 NextJS API 时出现顶级等待错误
【发布时间】: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


【解决方案1】:

在您所说的 cmets 中,您希望找到另一个解决方案,而不是在您正在使用的工具中启用顶级 await 实验。

为此,您必须调整模块代码以处理您还没有scheduled 集合的事实,您只有一个承诺。如果唯一导出的函数是handler,并且所有其他函数都将从handler 调用,那么在handler 中处理这个(不是双关语!)是有意义的,沿着这些行:

// A promise for the `scheduled` collection
const pScheduled = connectToDatabase().then(db => db.collection("scheduled"));

export default async function handler(req, res) {
    const scheduled = await pScheduled;
    await otherFunctionCalls(scheduled);
    // ...
}

const otherFunctionCalls = async (scheduled) => {
    // ...use `scheduled` here...
};

您可以通过多种方式对其进行调整,但从根本上讲,您将希望获得承诺(只需一次即可)和await 它可以在您需要其履行价值的任何地方获得其履行价值。 (为了避免重复:await 不会重新运行任何东西;如果承诺已经履行,它只会将承诺已经拥有的履行价值返还给您。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多