将sql查询结果读入js中的变量

时间:2016-08-18 07:05:20

标签: javascript

我有一个像这样的功能:

content = ck.getData();

然后像这样调用它:

function getNEO(state, callback) {
    var conString = "postgres://alexa:al@alexadb2.cgh333p2.us-east-1.redshift.amazonaws.com:5439/alexa";

    var client = new pg.Client(conString);
    client.connect();
    var data = '';
    var query = client.query("SELECT avg(Math) as math,  avg(Reading) as reading FROM sat_scores WHERE State = '" + state + "'");
    console.log("query is: %s", query);
    query.on('row', function(row) {
            console.log("Row cnt is: %s", row.math);
            console.log("row is: " + row)
            data += row;
        });
    console.log("made it");
    query.on('end', function() {
    callback(data);
        });
}

但结果将以 getNEO(st, function(results){ console.log("results: " + results); speechOutput = "There are " + results.math + " objects near the earth. "; callback(sessionAttributes, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession)); }); 的形式返回...如何将结果正确地调回句子?

1 个答案:

答案 0 :(得分:0)

您将结果作为回调中的字符串处理,您可以使用 + = 收集数据。

然后您可以访问结果,因为它应该是一个对象。

也许结果它是一个行对象数组,所以你应该连接每一行:

var data = [];
// ... code cut...
data.push(row);

results.math 应为 results [0] .math