簡體   English   中英

如何在另一個函數(NodeJS mysql)的查詢MySQL中使用“結果”變量(回調函數)

[英]How to use “results” variable (callback function) inside query mysql in another function (Nodejs mysql)

我有一個項目,用於存儲通過CentOS7中安裝的mosquitto(mqtt)傳遞到mysql數據庫的每條消息。 我使用Nodejs來存儲通過的消息。

然后,我在我的網站上顯示該消息。 我放置了“添加設備”功能,根據每個設備的總數據在數據庫中添加新表。 (如果我有一個名為“ device1”的設備來存儲溫度和濕度,它將創建一個名為“ device1”的新表以及3列,id,濕度和溫度。)

我有個問題。 我想在JavaScript中的查詢mysql中使用回調函數中的“結果”變量。 我想在該函數之外使用該變量。

這是代碼:

var sql= "SELECT count(*) AS hitung FROM information_schema.columns WHERE table_name = 'device' ";

connection.query(sql, function (error, results) {
    if (error) throw error;
    console.log(results[0].hitung);
});

基於我在上面給出的示例(device1)。 Console.log將打印“ 3”(因為3列)。

我想在另一個函數中使用它(results [0] .hitung值):

function example() {
    for (i=1; i<=results[0].hitung; i++) {
        console.log(i);
    };
};

但是它顯示了錯誤,我可以使用該變量。 我是網站開發的新手,因為我只對網絡感興趣。 對不起,我的英語不好,希望您能理解我的問題。 我是這個社區的新手。 謝謝。

我想在另一個函數中使用它(results [0] .hitung值)

為此,您需要從query回調函數中調用example ,就像使用console.log ,例如:

connection.query(sql, function (error, results) {
    if (error) throw error;
    example(results); // <===
});

那是因為:

  1. results僅限於該回調,並且
  2. 您必須等待回調才能獲得結果

您可能會考慮使用Promise和使用async函數 (創建和使用Promise)。 您可以使用util.promisify將Node回調樣式的函數轉換為util.promisify ,盡管大多數API都在積極采用util.promisify ,並且還有許多其他APIS的Promise包裝庫庫(例如, mysql-promise用於mysqlmysql2 )。 通過允許您使用僅用於同步代碼的標准流控制機制編寫異步代碼,可能會有所幫助。

您可以像這樣向函數添加參數:

function example(results) {
    for (i=1; i<=results.length; i++) {
        console.log(results[0].hitung)
    };
};

然后從查詢回調中調用該函數:

connection.query(sql, function (error, results) {
    if (error) throw error;
    example(results);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM