开发者

Problem with mysql wrapper function

开发者 https://www.devze.com 2023-03-22 18:50 出处:网络
I\'m playing with a Node.JS app for the first time, and so far I love it, but I\'m having a problem...

I'm playing with a Node.JS app for the first time, and so far I love it, but I'm having a problem...

I have written a wrapper function on the client.que开发者_开发知识库ry function that simply allows me to pass a parameter and it gets the query from an array of allowed queries...

    var runProcedure = function(proc, vars){
    var params;
    if(typeof vars != 'undefined'){
      params.concat(eval('(' + vars + ')'));
    }

    this._client.query(queries[proc], params, function(err, results, fields){
        if(err) { throw err; }
        if(results){
            return(results);
        }else{
            return "No data found.";
        }
    });
}

The function works correctly and if I console.log results, the data I want is there.. however, it's not getting returned to where I called it...

    var data = runProcedure(procedureName, parameters);
    console.log(data); // undefined

While troubleshooting, it seems that the query function is run asynchronously.... but this causes me a big problem. The runProcedure function is being called from within an http request handler.. so I need to be able to access the response variable. I guess I could pass it all the way down as a parameter... but that seems clumsy. What is the best code pattern to handle this? Should I set the response as a global var? can I run the mysql synchronously?

Cheers,

whiteatom


just pass your data to callback instead of returning with return

var runProcedure = function(proc, vars, callback) {

    var params;
    if(typeof vars != 'undefined'){
      params.concat(eval('(' + vars + ')'));
    }

    this._client.query(queries[proc], params, function(err, results, fields){
        if(err) { throw err; }
        if(results){
           callback(results);
        }else{
           callback('No data found.');
        }
    });

}

Now in http request handler:

// ...
function httpRequestHandler(req, resp)
{
    //...
    runProcedure(proc, vars, function(dbResp) {
        if (dbResp === 'No data found.')
        {
            // handle error
        } else {
            // do something with result
        }     
    })
}    
0

精彩评论

暂无评论...
验证码 换一张
取 消