[英]non-blocking in Node JS
I define a method that will get a value from the Database, I named it as getParam ()
as the following: 我定义了一个将从数据库中获取值的方法,将其命名为
getParam ()
,如下所示:
function getParam( tableName, paramName, id){
var param=0;
var query = client.query('SELECT '+ paramName + ' AS myparam FROM ' + tableName + ' where contest_id = ' + id);
query.on('row', function(row) {
param= row.myparam;
});
return param;
}
But I have a problem; 但是我有一个问题。 the callback function
param= row.myparam;
回调函数
param= row.myparam;
it returns param as undefined then it executes the callback function function(row) { param= row.myparam;}
. 它返回未定义的param然后执行回调函数
function(row) { param= row.myparam;}
。
However I want the callback function to run first then it returns the value in param. 但是我希望回调函数先运行然后返回参数值。 How can I do it since Node JS is asynchronous?
由于Node JS是异步的,我该怎么办?
Unless your database client has a synchronous mode - which is a bad idea in node anyways - you have to do it asynchronous, either with a callback or a promise: 除非您的数据库客户端具有同步模式(无论如何在节点中都是个坏主意),否则您必须使用回调或Promise进行异步操作:
function getParam( tableName, paramName, id, callback){
var param=0;
var query = client.query('SELECT '+ paramName + ' AS myparam FROM ' + tableName + ' where contest_id = ' + id);
query.on('row', function(row) {
param= row.myparam;
// call the callback from here
callback(param);
});
// removed your return statement, since there is nothing to return yet
// return param;
}
And call it: 并称之为:
getParam("mytable","myparam","256", function(param) {
// do what you want with param here
});
If you prefer a promise, then you can do it promise-style (any of several libraries is fine): 如果您更喜欢一个Promise,那么您可以按照Promise的方式进行操作(几个库中的任何一个都可以):
function getParam( tableName, paramName, id){
var param=0, defer = makeDeferSomehow();
var query = client.query('SELECT '+ paramName + ' AS myparam FROM ' + tableName + ' where contest_id = ' + id);
query.on('row', function(row) {
param= row.myparam;
// call the callback from here
defer.resolve(param);
});
// removed your return statement, since there is nothing to return yet
// return param;
// instead return the promise
return defer.promise;
}
And then you would call it: 然后您将其称为:
getParam("mytable","myparam","256").then(function(param) {
// do what you want with param here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.