I have a python background and is currently migrating to node.js. I have problem adjusting to node.js due to its asynchronous nature.

For example, I am trying to return a value from a MySQL function.

function getLastRecord(name) { var connection = getMySQL_connection(); var query_str = "SELECT name, " + "FROM records " + "WHERE (name = ?) " + "LIMIT 1 "; var query_var = [name]; var query = connection.query(query_str, query_var, function (err, rows, fields) { //if (err) throw err; if (err) { //throw err; console.log(err); logger.info(err); } else { //console.log(rows); return rows; } }); //var query = connection.query(query_str, function (err, rows, fields) { } var rows = getLastRecord('name_record'); console.log(rows);

After some reading up, I realize the above code cannot work and I need to return a promise due to node.js's asynchronous nature. I cannot write node.js code like python. How do I convert getLastRecord() to return a promise and how do I handle the returned value?

In fact, what I want to do is something like this;

if (getLastRecord() > 20) { console.log("action"); }

How can this be done in node.js in a readable way?

I would like to see how promises can be implemented in this case using bluebird.