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

90
Vistas
Async Express Router Function to MongoClient

I'm using Nodejs Express, the router middleware, in this case, MongoDB and using the POST method via JQuery ajax. Does anyone know why the router.post doesn't call, but a .get works. Does anyone know why the router.post doesn't get triggered when called as a Promise/async.

Async route here doesn't get called on ajax post.

async function asyncMain() {
  const uri = "mongodb endpoint";
  const client = new MongoClient(uri)

try {
    await client.connect().then(console.log('Connected to MongoDB'));

    //keeps awaiting cause it never executes.
    await pushToDB(client)
    //all mongoClient functions work with await here
    //Express http Post doesn't work with await here

} catch (e) {
    console.error(e);
} finally {
    await client.close();
  }
}

asyncMain().catch(console.error);

async function pushToDB(client) {
router.post('/', async(req, res, next) => {
    
    const result = await client.db('user').collection('notes').insertOne(req.body);
    console.log(`Results ${ result.insertedId }`);
  })
}

I tried using this async Middleware implementation with no results. Such as wrapping the post function's callback in asyncMiddleware to no avail.

 const asyncMiddleware = fn =>
 (req, res, next) => {
    Promise.resolve(fn(req, res, next))
        .catch(next);
 };

My working sync function for reference.

function main() {
   const uri = "mongodb endpoint";
   const client = new MongoClient(uri)

   client.connect().then(console.log('connected to DB'));
   router.post('/', (req, res) => {
    
   const result = client.db('user').collection('notes').insertOne(req.body);
   console.log(`Results ${ result.insertedId }`);
  })
}
about 4 years ago · Juan Pablo Isaza
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