简体   繁体   中英

how to pass variable from callback function to function call?

Here i am sending sensor data to database using simple javascript (johnny five) using this code

var five = require("johnny-five");
var pg = require("pg");
var conString = "pg://admin:raja@localhost:5432/data";
var client = new pg.Client(conString);

function call(n)
{
  client.connect();
  client.query("INSERT INTO sensordata (event) VALUES (n);");
}


var board = new five.Board();
board.on("ready", function() {

  var sensor = new five.Sensor.Digital(2);

  sensor.on("change", function() {
    var n = this.value;
    call(n);
  });
});

My question is can i pass the streaming data variable n in the sensor call back function to call method.

I think, what you're looking here is a simple query templating, supported by all sql clients:

client.query("INSERT INTO sensordata (event) VALUES ($1);", n);

This way you'll be able to pass the value of n variable to your SQL query.

Update: And you don't have to call client.connect() before every call to client.query . You should only call it once to establish DB connection, after that pg.Client will use it to send all subsequent requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM