sidorares / sidorares/node-mysql2

Promise wrapper on createConnection is problematic in top-level code

Open
#466 10 comments 6 reactions 0 assignees View on GitHub

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.