2016-03-08 78 views
1

我想打电话给一个function.so内的回调函数,我不知道该怎么做如何在函数内部使用回调函数?

function call(){ 
    pg.connect(conString, function(err, client, done) { 
    if(err) { 
     return console.error('error fetching client from pool', err); 
    } 
    client.query('INSERT into post1 (data) VALUES ($n)', function(err, result) { 
     //call `done()` to release the client back to the pool 
     done(); 

     if(err) { 
     return console.error('error running query', err); 
     } 
     console.log(result.rows[0].number); 
     //output: 1 
    }); 
    }); 
} 
board.on("ready", function() { 

    // Create a new generic sensor instance for 
    // a sensor connected to an analog (ADC) pin 
    var sensor = new five.Sensor("A0"); 

    // When the sensor value changes, log the value 
    sensor.on("change", function() { 
    var n = this.value(); 
    //i want to call that function here 
    }); 
}); 

,我也想调用这个函数在另一个回调函数,这是做正确的方式或建议我是正确的。

回答

1

你可以做这样的事情,在那里你传递一个函数到你的函数中。所以在这种情况下回调将是一个函数。

function call(callback){ 
    pg.connect(conString, function(err, client, done) { 
    if(err) { 
     return console.error('error fetching client from pool', err); 
    } 
    client.query('SELECT $1::int AS number', ['1'], function(err, result) { 
     //call `done()` to release the client back to the pool 
     done(); 
     callback(); //execute here or wherever 
     if(err) { 
     return console.error('error running query', err); 
     } 
     console.log(result.rows[0].number); 
     //output: 1 
    }); 
    }); 
} 

,那么你可以这样调用它

call(function(){ 
    //some logic here. 
}) 

或:

var someFunction = function() 
{ 
    //do something 
} 

call(someFunction); 
+0

为什么ü通过回调呢? – RajaRaman

+0

抱歉一定没有理解你的问题,你想达到什么目的? – JanR

+0

回调(结果); –