2017-09-12 45 views
0

我正在使用Express和MySQL,我希望能夠從connection.query中檢索數據,然後在同一路線內的其他功能中使用該數據。我希望能夠使用app.post中另一個函數connection.query內部的數組,但是我不知道這樣做的最佳方式是什麼。我曾嘗試使用由Express所需的單獨文件編寫的實用函數,但是我無法從MySQL連接中獲取數據到寫入外部文件的函數中,我甚至不確定這是否是正確的方法做我想做的事。如何使用Express路由中的另一個函數/多個函數來處理數據庫中的數據?

這裏是我的代碼,我希望做的是可能能夠把forEach方法自身功能的內,然後使用另外一個函數返回數組的查詢後,用它做什麼等等。

app.post('/submit', function(req, res) { 
    var getPosition = "SELECT ID, position FROM routes"; 
    var posArray = []; 
    connection.query(getPosition, function(err, results) { 
    if (err) throw err; 
    results.forEach(function(item) { 
     posArray.push(item.position); 
     return posArray; 
    }); //end if 
    }); 
}); // end app.post 
+2

你'return'是沒有意義的。 – SLaks

+1

您需要使用回調或承諾。 – SLaks

回答

0

您可以鏈的中間件來實現這一點:

app.post('/submit', getDataFromDatabase, processData); // end app.post 

function getDataFromDatabase(req, res, next) { 
    var getPosition = "SELECT ID, position FROM routes"; 
    var posArray = []; 
    connection.query(getPosition, function(err, results) { 
    if (err) throw err; 
    results.forEach(function(item) { 
     posArray.push(item.position); 
     req.posArray = posArray; //attach the data that you want to use later to your req object 
    }); //end if 

    next(); //Call the next middleware; 
    }); 
} 

function processData(req, res, next){ 
    //Do whatever you want with req.posArray; 

    res.json(posArray); //respond to the client with the posArray (or whatever the client asked for) 
} 
+0

謝謝!將這些中間件包含在服務器內部,但是在你之前展示的app.get/app.post方法之外,可以嗎? – brekki

+0

是的。它們的行爲與內聯函數相同,但更易於閱讀。 –

相關問題