Promise wrapper on createConnection is problematic in top-level code
See original GitHub issueThe non-promise version of createConnection is not asynchronous. Unlike the database calls, no callback is required here.
var connection = mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
However, the promise wrapper version comes back as a promise.
let connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
This wouldn’t be a problem, except that Node/V8 don’t currently allow await outside of an async function, including at the top level of an app. This means that the example code doesn’t work when you drop it into a simple Node app. The easy solution that I’ve come up for this, is to wrap createConnection in an IIFE.
let connection
(async function() {
try {
connection = await mysql.createConnection(dbconfig)
} catch(err){
console.error(err)
}
})()
This seems unnecessarily complex, since this isn’t a method that needs to be async. I would propose that createConnection remains a synchronous function, the same way it is in the non-promise version. I’m also having difficulty finding an easy way to stick my DB stuff into a module with this pattern.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:6
- Comments:10 (4 by maintainers)
Yea, in fact was just pulling out the AWS certs to share right now :waves:
hi @jdhiro
I see your point, I wish 7+ node had repl and top level module wrapper async functions
Here are my thoughts: the only correct way of using connection, even in simple script is like this:
async
.createConnection()
helps a little with this, in a way that if there is connection error and no command error can be caught. Unfortunately it’s still possible for ‘error’ connection event to crash process so you must attach listener. My advise is to always use pool, even in scripts - pool handles this error logic automatically.I’ll think about changing
.createConnection()
to be sync. Maybe it’s possible to make this backwards compatibleas a work around - if you prefer async wrappers but want to have
.createConnection()
in top lewel of script without extra wrapping - just don’t use await: