sidorares / sidorares/node-mysql2
Promise wrapper on createConnection is problematic in top-level code
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 4.4k
- Forks
- 680
- Avg merge
- 9h 7m
- Merged PRs (30d)
- 59
Description
The 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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the createConnection entry point and compare the promise-wrapper behavior with the non-promise version described in the issue. Review the existing discussion and examples first; done means the promise API supports the intended simple top-level Node usage without requiring the proposed IIFE workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mysql, node.js, typescript
- Domain
- database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100