app.use(async function(req, res, next) {
try {
var myres = await new Promise((resolve, reject) => {
mysql_connection.query("select * from Users;", (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
} catch (error) {
console.log(error);
}
});
Question is. using async function to be able to use await for DB queries is ok? i am afraid that it can cause some problems on expressjs side.
To use async/await, you need to use the async keyword when you define a request handler. (Note: These request handlers are also called “controllers”. I prefer calling them request handlers because “request handlers” is more explicit). Once you have the async keyword, you can await something immediately in your code.
In Node. js, input and output activities like network requests are done asynchronously. As Axios uses Promises to make network requests, callbacks are not an option when using this library. We interact with Axios using Promises, or the async/await keywords which are an alternative syntax for using Promises.
In closing, utilizing async / await as your Express middleware implementation helps keep your code reusable, readable, and up-to-date with current coding conventions.
We can convert this into a function that uses async/await in Express by first marking the handler as an async function. Then we can call await inside of the request handler. What about error handling? If the above function would have worked and you already knew about async/await syntax, this blog post would have been a waste of your time.
I prefer calling them request handlers because request handlers are more explicit). Once you have the async keyword, you can await something immediately in your code. Let’s say you want to create a user through a POST request. To create a user, you need to pass in a firstName and an email address.
Using async/await on a REST endpoint In order to use the async/await model in a REST endpoint, we must consider that an "await for a promise" command requires an async function to call them. A fairly simple way of doing it is having the async keyword on our last RESTful endpoint's function.
This request results in an error. Unfortunately, Express will not be able to handle this error. You’ll receive a log like this: To handle an error in an asynchronous function, you need to catch the error first. You can do this with try/catch.
async..await
is syntactic sugar for promises, and a promise is just a pattern that relies on callbacks. The use of async
functions is acceptable wherever they are supported by the environment. async..await
is supported since Node.js 7.6.0.
async
function always returns a promise. As long as this implicit return value doesn't cause problems, it's perfectly fine everywhere, including Express. It doesn't matter whether it's used for database queries or anything else.
Unless API supports promises, errors should be entirely handled in async
function. Function body should be wrapped with try..catch
to rule out unhandled rejections which may result in exceptions in future Node versions.
The original code contains no next
calls and just suppresses an error. As a rule of thumb, async
middleware should be structured like that:
app.use(async function(req, res, next) {
try {
...
next();
} catch (error) {
next(error);
}
});
Async await can be used with no problem for DB queries. You could use try catch however there is a more elegant solution which allows you to use the error handling middleware which express offers:
You wrap your middleware with this function:
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
Then you can use it in the following manner:
const asyncMiddleware = require('./utils/asyncMiddleware');
router.get('/', asyncMiddleware(async (req, res, next) => {
/*
if there is an error thrown in getUserFromDb, asyncMiddleware
will pass it to next() and express will handle the error;
*/
const user = await getUserFromDb({ id: req.params.id })
res.json(user);
}));
If an error is thrown the control will be handed over to the error handling middleware which is middlware which has four arguments like this:
app.use(function (err, req, res, next) {
// your error code
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With