generic pool function return result of callback

时间:2015-08-07 02:37:02

标签: javascript node.js

i am very novice to nodejs, i am using generic-pool with mariasql. everything works fine. But i moved my code inside a function like this and i am not quiet sure what is the nodejs way of event handling so that i can actually get the results from the function back

var pooledQuery = function (query) {
    var result;
    //return here will be the return value of pool.acquire
    pool.acquire(function(err, client) {
        var db;
        if (err != null) {
            console.log(err)
            return err;
        }

        result = [];
        db = client.query(query);
        db.on('result', function(res) {
            return res.on('row', function(row) {
                console.log(row);
                return result.push(row);
            }).on('error', function(err) {
                console.log('error');
            }).on('end', function(info) {
                return result;
            });
        }).on('end', function() {
            pool.release(client);
            return result; <-- i want to know how i can obtain this return value outside of this function?? 
        });
    });
    //since pool.acquire is non-blocking the code will reach here and return an empty value
    return result;
};

what is the nodejs way of being able to accomplish something like this using the function above

var result = pooledQuery("SELECT foo, bar FROM foobar");

i am using this generic-pool from nodejs https://github.com/coopernurse/node-pool

1 个答案:

答案 0 :(得分:1)

返回承诺

   var pooledQuery = function(query) {
       return new Promise(function(resolve, reject) {
           //return here will be the return value of pool.acquire
           pool.acquire(function(err, client) {
             var db;
             if (err != null) {
               reject(err); // oh no! error, let the promise know that it failed
             }

             result = [];
             db = client.query(query);
             db.on('result', function(res) {
               return res.on('row', function(row) {
                 console.log(row);
                 return result.push(row);
               }).on('error', function(err) {
                 reject(err) // here too
               }).on('end', function(info) {
                 return result;
               });
             }).on('end', function() {
               pool.release(client);
               resolve(result); // your promise is resolved, 
               // any ".then" callback applied to it will be called now. 
               // i.e `pooledQuery(query).then(function(result){console.log(result)})
             });
           });
         }
       };

像这样使用

pooledQuery("SELECT foo, bar FROM foobar").then(function(result){console.log(result);})

有许多承诺库。 Examples using bluebird