Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

432
Visualizações
top-level-await error when using NextJS API

I'm building an api with NextJS and MongoDB. I do a basic setup on the top of the API file:

const { db } = await connectToDatabase();
const scheduled = db.collection('scheduled');

and I continue the code with my handler function:

export default async function handler(req, res) {
  otherFunctionCalls()
  ...
}

const otherFunctionCalls = async () => {
  ...
}

I know await will work only within an async function, but I would like to use the scheduled constant in other functions what the handler calls, that's why I need to call it on the top.

If I put the constant to every single function, then it's code duplication.

What's the best practice to access to scheduled constant? Should I add the otherFunctionCalls declaration into the handler function?

The complete error what I got:

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)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the comments you've said you want to find another solution rather than enabling the top-level await experiment in the tool you're using.

To do that, you'll have to adjust the module code to handle the fact that you don't have the scheduled collection yet, you just have a promise of it. If the only exported function is handler and all of the other functions are going to be called from handler, they it makes sense to handle that (no pun!) in handler, along these lines:

// 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...
};

There are lots of ways you might tweak that, but fundamentally you'll want to get the promise (just once is fine) and await it to get its fulfillment value anywhere you need its fulfillment value. (For the avoidance of double: await doesn't re-run anything; if the promise is already fulfilled, it just gives you back the fulfillment value the promise already has.)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda