CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 63 forks source link

Documentation advise passing connection to parent context. #63

Closed Naouak closed 7 years ago

Naouak commented 7 years ago

The readme contains the following sample of code:

var mysql = require('promise-mysql');
var connection;

mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
}).then(function(conn){
    connection = conn;
    return connection.query('select `id` from hobbits where `name`="frodo"');
}).then(function(rows){
    // Query the items for a ring that Frodo owns.
    var result = connection.query('select * from items where `owner`="' + rows[0].id + '" and `name`="ring"');
    connection.end();
    return result;
}).then(function(rows){
    // Logs out a ring that Frodo owns
    console.log(rows);
});

I'm not sure it's good practise to put the connection in the parent context (the line with connection = conn). I think the connection should be provided to the next element in the promise through the promise like this:

const mysql = require('promise-mysql');
const connectionPromise = mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
});
connectionPromise.then(function(connection){
    return Promise.all([connection.query('select `id` from hobbits where `name`="frodo"'), connectionPromise]);
}).then(function([rows, connection]){
    // Query the items for a ring that Frodo owns.
    return Promise.all([connection.query('select * from items where `owner`= ? and `name`="ring"', [rows[0].id]), connectionPromise]);
}).then(function([rows, connection]){
    connection.end();
    // Logs out a ring that Frodo owns
    console.log(rows);
});
CodeFoodPixels commented 7 years ago

It entirely depends on what you want to do. Your example makes sense for a script.