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

92
Visualizações
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 à 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