2016-12-04 16 views
0

私のindex.jsファイルに以下のコードがあります。私はプロファイルテーブルのデータを印刷することができます。そして私は同じ(index.njk)ページでもレジュームテーブルのデータを印刷する必要があります。しかし、私はできませんでした。私もsimilar questionが見つかりましたが、私は新しいですし、私のプロジェクトに従ってそれらのコードを変更することができませんでした。あなたは助けてもらえますか?NodeJs - 複数のSELECTクエリの後に同じページをレンダリングする

var express = require('express'), 
path = require('path'), 
bodyParser = require('body-parser'), 
router = express.Router(), 
app = express(); 
var pg =require('pg'); 

// DB Connect string 
var connect = { 
user: 'arslan', 
database: 'resumedb', 
password: '1984', 
host: 'localhost', 
port: 5432, 
max: 10, 
idleTimeoutMillis: 30000, 
}; 

router.get('/', function(req, res){ 
pg.connect(connect, function(err, client, done, skills){ 
    if(err){ 
    return console.error('errrr', err) 
    } 
    //Get Profile Informations 
client.query('select id,fname,lname,title,description,profileimage from profile', function(err, result){ 

    if(err){ 
     return console.error('error running query', err); 
    } 
    if(result.rows.length > 0) { 
      res.render('index.njk', { 
       profileName: result.rows[0].fname, 
       profileLName: result.rows[0].lname , profileTitle: result.rows[0].title 
       , profileDesc: result.rows[0].description 
       , profileImage: result.rows[0].profileimage 
      }); 

     console.log(result.rows[0].profileimage); 
    }else { 
     console.log('No rows found in DB'); 
    } 
    done() 
}); 
}); 
}); 
+0

チェックアウト、お問い合わせください[PG-約束] (https://github.com/vitaly-t/pg-promise)、従属クエリと独立クエリの両方を構造化する最も簡単な方法です) –

答えて

0

すべての非同期用の最適な解決策は、約束を使用することです。 あなたのコードは接続プールにconfigを使用しますが、後でプールを使用しませんが、しばしばプールを使用することをお勧めします。あなたはdb.query('select 1 + 1').then(rows => { /* your code */}).catch(err => { next(err) })を使用することができ、単一のクエリを作成したい場合は あなたのルートで、その後

// ... 
const db = require('./db') 

router.get('/', function(req, res, next) { 

    let profileQuery = db.queryOne('select id,fname,lname,title,description,profileimage from profile') 
    let resumeQuery = db.query('???') 
    Promise.all([profileQuery, resumeQuery]).then(([profile, resume]) => { 
    if (!profile) { 
     return res.status(404).send('Profile not found') // error page 
    res.render('index.njk', { 
      profileName: profile.fname, 
      profileLName: profile.lname, 
      profileTitle: profile.title, 
      profileDesc: profile.description, 
      profileImage: profile.profileimage 
     }) 
    }).catch(err => { 
    next(err) 
    }) 

}) 

をデシベル

const pg = require('pg') 

const connect = { // Normaly you would use an config file to store this information 
    user: 'arslan', 
    database: 'resumedb', 
    password: '1984', 
    host: 'localhost', 
    port: 5432, 
    max: 10, 
    idleTimeoutMillis: 30000 
} 

let pool = new pg.Pool(config) 

exports.query = (query, values) => { 
    return new Promise((resolve, reject) => { 
    pool.connect(function(err, client, done) { 
     if (err) 
     return reject(err) 
     client.query(query, values, (err, result) => { 
     done() 
     if (err) 
      return reject(err) 
     resolve(result) 
     }) 
    }) 
    }) 
} 

exports.queryOne = (query, values) => { 
    return new Promise((resolve, reject) => { 
    this.query(query, values).then(rows => { 
     if (rows.length === 1) { 
     resolve(rows[0]) 
     } else if (rows.length === 0) { 
     resolve() 
     } else { 
     reject(new Error('More than one row in queryOne')) 
     } 
    }).catch(err => { 
     reject(err) 
    }) 
    }) 
} 

pool.on('error', function (err, client) { 
    console.error('idle client error', err.message, err.stack) 
}) 

を照会する新しいモジュールdb.jsを作成します。 多くの場合、1つの行だけが必要なので、queryOneを使用できます。 undefinedが返されます。行、必要な行、または複数行のエラー

next()引数にエラーがあると、エラーハンドラが呼び出されます。あなたが何かを理解しないならば、それは最初に複雑になる可能性があるため、そこには、エラーを記録し、あなたがその

ために独自に作成する必要がある500を返すことができます:)

+0

コードは本当に複雑です:)私はそれに取り組むのに多くの時間が必要です。もし動作すればダニ。アドバイスをありがとう。 –

+0

こんにちは@Julian、私はこのコードを使用することができませんでした。私は[リンク](http://stackoverflow.com/questions/28128323/rendering-view-after-multiple-select-queries-in-express)の答えでロジックを使用しました。答えに自分のコードを分けています。彼らは正常に動作しているが、私はPostgreSQLに接続するより良い方法を見つける必要があります。私のウェブページは2回目のクリックの後に詰まっているので。私のコードを見直して、私が接続について助けてくれますか? –

+0

なぜあなたはそれを使用できませんでしたか?あなたのコードでは、querysは次々に実行されますが、同時に実行されるのではありませんが、より速い応答時間を必要としない場合はokです。 2番目の呼び出しでエラーが発生しました( 'if(err){console.log(err)}'やエラーハンドラを使用してください)。 1つの接続と1つの接続プールに複数のコードを混在させることが間違いである可能性があります。ここでの例を見てくださいhttps://github.com/brianc/node-postgresあなたがclient.endをdoneの代わりに使用する単一の接続の場合 – Julian

関連する問題