Back to Node Mysql2

Promise Wrappers

website/docs/documentation/promise-wrapper.mdx

3.22.33.4 KB
Original Source

Promise Wrappers

In addition to errback interface there is thin wrapper to expose Promise-based api

Basic Promise

js
/* eslint-env es6 */
const mysql = require('mysql2/promise'); // or require('mysql2').createConnectionPromise
mysql
  .createConnection({
    /* same parameters as for non-promise createConnection */
  })
  .then((conn) => conn.query('select foo from bar'))
  .then(([rows, fields]) => console.log(rows[0].foo));
js
const pool = require('mysql2/promise').createPool({}); // or require('mysql2').createPoolPromise({}) or require('mysql2').createPool({}).promise()
pool
  .getConnection()
  .then((conn) => {
    const res = conn.query('select foo from bar');
    conn.release();
    return res;
  })
  .then((result) => {
    console.log(result[0][0].foo);
  })
  .catch((err) => {
    console.log(err); // any of connection time or query time errors from above
  });

ES7 Async Await

js
async function example1() {
  const mysql = require('mysql2/promise');
  const conn = await mysql.createConnection({ database: test });
  const [rows, fields] = await conn.execute('select ?+? as sum', [2, 2]);
  await conn.end();
}

async function example2() {
  const mysql = require('mysql2/promise');
  const pool = mysql.createPool({ database: test });
  // execute in parallel, next console.log in 3 seconds
  await Promise.all([
    pool.query('select sleep(2)'),
    pool.query('select sleep(3)'),
  ]);
  console.log('3 seconds after');
  await pool.end();
}

Explicit Resource Management (await using)

With Explicit Resource Management, connections and pools are automatically cleaned up when they go out of scope — no need to manually call .end() or .release().

ts
import mysql from 'mysql2/promise';

{
  await using conn = await mysql.createConnection({ database: test });
  const [rows, fields] = await conn.execute('select ?+? as sum', [2, 2]);
  // conn.end() is called automatically when leaving the scope
}
ts
import mysql from 'mysql2/promise';

{
  await using pool = mysql.createPool({ database: test });

  // execute in parallel, next console.log in 3 seconds
  await Promise.all([
    pool.query('select sleep(2)'),
    pool.query('select sleep(3)'),
  ]);
  console.log('3 seconds after');
  // pool.end() is called automatically when leaving the scope
}
ts
import mysql from 'mysql2/promise';

const pool = mysql.createPool({});

{
  await using conn = await pool.getConnection();
  const res = await conn.query('select foo from bar');
  console.log(res[0][0].foo);
  // conn.release() is called automatically when leaving the scope
}

:::tip await using and using leverage Explicit Resource Management to automatically call .end() or .release() when the variable goes out of scope, so you never forget to clean up connections. :::

With CO

js
const mysql = require('mysql2');
const co = require('co');
co(function* () {
  const c = yield mysql.createConnectionPromise({
    user: 'root',
    namedPlaceholders: true,
  });
  const rows = yield c.query('show databases');
  console.log(rows);
  console.log(yield c.execute('select 1+:toAdd as qqq', { toAdd: 10 }));
  yield c.end();
});

Examples in /examples/promise-co-await