Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

433
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda