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);
});
The readme contains the following sample of code:
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: