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 }`);
})
}