Skip to content

Instantly share code, notes, and snippets.

@popovkos
Last active August 2, 2019 08:02
Show Gist options
  • Save popovkos/dfc4dfa52dc4ebb448d44c3912be140a to your computer and use it in GitHub Desktop.
Save popovkos/dfc4dfa52dc4ebb448d44c3912be140a to your computer and use it in GitHub Desktop.
const mysql = require('mysql');
// standart example from mysql documentation
(function test1() {
const pool = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: '1234',
database: 'test',
});
pool.query('select * from person', (error, results, fields) => {
if (error) throw error;
console.log('The solution is: ', results); // query results available only here, inside callback
});
}());
// using new Promise
function modifiedQueryFunction(pool, query) {
return new Promise((resolve, reject) => {
pool.query(query, (error, results, fields) => {
if (error) {
reject(error);
}
resolve(results);
});
});
}
(async function test2() {
let pool;
try {
pool = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: '1234',
database: 'test',
});
const query = 'select * from person';
const result = await modifiedQueryFunction(pool, query);
console.log(result); // query result available here, outside of the callback
// ... do whatever you need, without possibility for callabck hell
} catch (e) {
console.log(e);
} finally {
pool.end();
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment