Last active
August 2, 2019 08:02
-
-
Save popovkos/dfc4dfa52dc4ebb448d44c3912be140a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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