node mysql promise,使用Promise处理Node.js中的MySQL返回值

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.

解决方案

This is gonna be a little scattered, forgive me.

First, assuming this code uses the mysql driver API correctly, here's one way you could wrap it to work with a native promise:

function getLastRecord(name)

{

return new Promise(function(resolve, reject) {

// The Promise constructor should catch any errors thrown on

// this tick. Alternately, try/catch and reject(err) on catch.

var connection = getMySQL_connection();

var query_str =

"SELECT name, " +

"FROM records " +

"WHERE (name = ?) " +

"LIMIT 1 ";

var query_var = [name];

connection.query(query_str, query_var, function (err, rows, fields) {

// Call reject on error states,

// call resolve with results

if (err) {

return reject(err);

}

resolve(rows);

});

});

}

getLastRecord('name_record').then(function(rows) {

// now you have your rows, you can see if there are <20 of them

}).catch((err) => setImmediate(() => { throw err; })); // Throw async to escape the promise chain

So one thing: You still have callbacks. Callbacks are just functions that you hand to something to call at some point in the future with arguments of its choosing. So the function arguments in xs.map(fn), the (err, result) functions seen in node and the promise result and error handlers are all callbacks. This is somewhat confused by people referring to a specific kind of callback as "callbacks," the ones of (err, result) used in node core in what's called "continuation-passing style", sometimes called "nodebacks" by people that don't really like them.

For now, at least (async/await is coming eventually), you're pretty much stuck with callbacks, regardless of whether you adopt promises or not.

Also, I'll note that promises aren't immediately, obviously helpful here, as you still have a callback. Promises only really shine when you combine them with Promise.all and promise accumulators a la Array.prototype.reduce. But they do shine sometimes, and they are worth learning.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值