我想從Postgres DB獲取資料,并使用Node JS將該資料傳輸到Vue前端
在這里,我創建了單獨的函式來獲取資料。這是我的功能定義。
function fetchshop(){
pool.query('SELECT * FROM shops',(err, shps) =>{
if (err){
throw err
}
else {
shopdetails=shps.rows;
console.log(shopdetails) // Here the data is printed in console
return shopdetails;
}
});
}
我能夠從該pool.query部分在控制臺中列印資料行,但是在函式呼叫部分,當我嘗試在它顯示的控制臺中列印回傳的資料時undefined。這是我的函式呼叫代碼
events=[];
shopdetails=[];
app.get("/home",async (request,response,err)=>{
events = fetchshop();
console.log(events) // This prints 'undefined' in console
response.send(events); // I want to send this events.
})
uj5u.com熱心網友回復:
這樣做的原因是,您的內部代碼fetchshop異步運行,但您期望同步行為。您的query方法接受在從 Postgres 獲取資料后異步執行的回呼。fetchshop在查詢成功之前完成,因此不回傳任何內容,undefined。您必須承諾您的代碼或使用作為引數傳遞的回呼fetchshop。
function fetchshop(callback) {
pool.query("SELECT * FROM shops", (err, data) => {
if(err) {
return callback(err);
}
return callback(undefined, data.rows);
});
}
app.get("/home", (req, res, next) => {
fetchshop((err, data) => {
if(err) {
return next(err);
}
res.status(200).send(data);
});
});
這樣,您的fetchshop方法callback在完成異步資料獲取后將自己稱為一個偵聽器,稱為。app.get("/hello", ...)當加載資料并且可以發送請求時,您的 HTTP 請求偵聽器會收到異步通知。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/395499.html
標籤:节点.js PostgreSQL的 功能 Vue.js 返回值
