Search code examples
javascriptpromisemysql2

Do i have to always wrap an argument to a promise when doing promise -then-catch


Background on the question, Im using express,node and mysql2.

Basically, I'm trying to ping a database to verify the connection. By using the Promise-then-catch syntax, I have to pass conn to the next then as .ping() do not return anything, and i wont be able to release the connection without this way of writting.

My question is this,

const p0 = Promise.resolve(conn) 

const p0 = conn

both works, are there any reason why i should wrap it in promise? Will there be any issue if i dont do so?

const mysql = require('mysql2/promise');


const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT) || 3306,
  database: process.env.DB_NAME || 'playstore',
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  connectionLimit: parseInt(process.env.DB_CONNECTION_LIMIT) || 4,
  timezone: '+08:00',
});

const SQL_GET_APP_CATEGORIES = 'select distinct category from apps ';

pool
  .getConnection()
  .then((conn) => {
    console.info('ping-ing DB');
    const p0 = Promise.resolve(conn);
    const p1 = conn.ping();
    return Promise.all([p0, p1]);
  })
  .then((results) => {
    const conn = results[0];
    //Release connection
    conn.release();
    app.listen(PORT, () => console.log(`Running on http://localhost:${PORT}`));
  })
  .catch((e) => {
    console.log(`Cannot start server ${e}`);
  });


Solution

  • Instead of this:

    pool
      .getConnection()
      .then((conn) => {
        console.info('ping-ing DB');
        const p0 = Promise.resolve(conn);
        const p1 = conn.ping();
        return Promise.all([p0, p1]);
      })
    

    You can write it this way:

    pool
      .getConnection()
      .then((conn) => {
        console.info('ping-ing DB');
        return conn.ping().then(() => conn);
      })
    

    Which just basically says that when conn.ping() resolves, you want to make the resolved value of the returned promise be conn. Or, if it rejects, the returned promise will be rejected.


    The way you were doing it, there is no reason to wrap it in a promise. You can pass a value to Promise.all() if you want as in:

    return Promise.all([conn.ping(), conn]);
    

    But, my recommendation at the beginning of this answer would be cleaner since you're not interested in the resolved value from conn.ping() and you only have one promise (thus there's no real reason to use Promise.all() with only a single promise).