2016-08-19 39 views
0

我有下面的代碼:MySQL,Node.js順序操作 - 我該怎麼做?

function query1() { 

var defered = Q.defer(); 

console.log("In query1"); 

var connection = mysql.createConnection({ 
    host: '........', 
    user: 'm...c....a.....i', 
    password: '......Z....9...K', 
    database: '.....ol' 
}); 

connection.connect(function(err) { 
    if (!err) { 
     console.log("Database is connected ..."); 
    } else { 
     console.log("Error connecting database ..."); 
    } 
}); 

sql = '' + 
    'select c.ID as CENA_ID, ' + 
    '  c.I_KEY as CENA_NUMERO, ' + 
    '  c.NM_CENA as CENA_NOME, ' + 
    '  b.DS_MAC as MAC_BOX, ' + 
    '  v.DS_CLIENTID as ALEXA_ID, ' + 
    ' v.FK_ID_GRUPO as GRUPO_ID ' + 
    ' from TB_DISPOSITIVOS_VOZ v ' + 
    '  inner join TB_GRUPOS g ' + 
    '  on g.ID = v.FK_ID_GRUPO ' + 
    '  inner join TB_CENAS c ' + 
    '  on g.ID = c.FK_ID_GRUPO ' + 
    '  inner join TB_CENTRAIS b ' + 
    '  on g.ID = b.FK_ID_GRUPO ' + 
    'where v.DS_CLIENTID = "' + userId + '" ' + 
    'and lower(c.NM_CENA) like "%' + sceneName.toLowerCase() + '%"'; 


console.log("Created query"); 

try{ 

    connection.query(sql, function(erro, rows, fields) { 

     if (!erro) { 

      console.log("Executed query verifying the userId"); 

      contador = 0; 

      if (rows.length > 0) { 

       cena_id = rows[0].CENA_ID; 
       cena_numero = rows[0].CENA_NUMERO; 
       cena_nome = rows[0].CENA_NOME; 
       alexa_id = rows[0].ALEXA_ID; 
       grupo_id = rows[0].GRUPO_ID; 
       mac_box = rows[0].MAC_BOX; 

       contador = contador + 1; 

      } 

      console.log("contador: " + contador); 

     } else { 
      console.log("Error - getting the Alexa register in database" + erro); 
      context.fail("Error - getting the Alexa register in database" + erro); 
     } 

    }); 


}catch (ex){ 
    console.log("exception: " + ex); 
} 

}

而這種代碼以及:

Q.all([query1()]).then(function(results) { 

     console.log("Q.all log function"); 

     if (contador > 0) { 

      console.log("contador > 0"); 

      var client = mqtt.connect('mqtt://.............com'); 
      console.log("connected to MQTT broker"); 

      var buffer = [26, 
       0,0,0,0,555,645,0,0,0,0,0, 
       0,5555,2,Math.floor((Math.random() * 200) + 1), 
       0,0,0,333,13,4,0,1,0, 
       cena_numero 
      ]; 

      console.log("Created buffer"); 

      client.on('connect', function() { 

       client.publish('n/c/' + mac_box + '/app', buffer); 

       console.log("sent MQTT"); 

      }); 

      speechOutput = "Command " + sceneName + " executed successfully"; 
      repromptText = ""; 
      console.log("Process executed successfully") 

     } else { 

      console.log("contador <= 0"); 

      speechOutput = "This command was not found!"; 
      repromptText = ""; 

     } 

    }, function (reason) { 

     console.log("reason: " + reason); 

    }); 

我怎樣才能爲第二代碼只做執行,如果第一query1()正確執行?因爲在函數query1()中我有一個MySQL查詢,並且我只能在查詢的結果之後繼續進程。

任何人都可以幫到我嗎?

非常感謝!

回答

0

我解決我的問題與async包這樣的:

var async = require('async'); 

async.series([ 
      function(callback) { 

       //action 1... 

      }, 
      function(callback){ 

       //action 2... 
      } 
     ], function(err) { 
      if (err) { 
       speechOutput = "Scene not found!"; 
       repromptText = "Please try again."; 
      } 
      console.log("Before speechOutput"); 
      callback(sessionAttributes, 
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession)); 
     }); 
1

你錯過了關於Node.js中的回調和異步行爲的一些關鍵概念。您正在使用「Q」庫(順便說一句,我建議嘗試藍鳥)來處理承諾,但是您的「query1」函數不會返回承諾。這就是query1執行的原因,但是您的「Q.all日誌功能」將在query1完成之前執行。

您可以構建這樣的,而不是你的代碼(我會,因爲我更熟悉它給人以青鳥爲例):

var Promise = require('bluebird'); 

var _connection; 

function query1() { 
    return new Promise(resolve, reject) { 
    //open your connection 
    connection.open(function (err, connection) { 
     if (err) return reject(err); 

     _connection = connection; 
     //do your query 
     _connection.query(sql, [params], function (err, data) { 
     if (err) return reject(err); 
     else resolve(data); 
     }); 
    }); 
    }); 
} 

function query2(data) { 
    return new Promise(resolve, reject) { 
    //do your query, using data passed in from query1 
    _connection.query(sql, [params], function (err, data) { 
     if (err) return reject(err); 
     else resolve(data); 
    }); 
    }); 
} 


query1 
    .then(function (data) { query2(data); }) 
    .catch(function (err) { 
    console.log('error:', err); 
    }); 

此外,僅供參考,像這樣串聯SQL字符串是不,不,這將打開你到一個SQL注入攻擊:

like "%' + sceneName.toLowerCase() + '%"

相反,使用like "%?%"並調用你的SQL與connection.query(sql, [sceneName], function(err, data) {})。希望這可以幫助。

+0

這藍鳥包是'意外的標記{' –

+0

我沒有運行上面的代碼,所以你需要編輯它,使其跑。這是爲了提供信息的目的,希望能指出你正確的方向。 –