[英]Execute Several database queries (promises) sequentially
數據庫查詢本身不是問題 - 它們工作正常。
問題是,我需要按順序執行所有這些:
DELETE FROM myTable;
INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z);
SELECT * FROM myTable;
而且無論我嘗試什么,我都無法弄清楚如何在 Node 中做到這一點。 這個問題似乎是訪問量最大的解決方案,它會讓我做這樣的事情( client
來自pg
,應該返回承諾):
// client is my database client, has already been initialized
// f is an object corresponding to my database
var res;
Promise.resolve()
.then(() => {
console.log("Deleting");
return client.query("DELETE FROM FileFormat");
})
.then(() => {
console.log("Inserting");
return client.query("INSERT INTO myTable(c1, c2, c3) VALUES ($1, $2, $3)", [f.x, f.y, f.z]);
})
.then(() => {
console.log("Selecting");
return client.query("SELECT * FROM FileFormat").then((err, result) => res = result.rows)
})
.then(() => {
console.log("Finished");
console.log(res);
})
我希望它打印Deleting
,然后是Inserting
,然后是Selecting
,然后是Finished
,然后是我剛剛插入數據庫的數據。
相反,它正在打印Deleting
然后什么也不做。
我不想無限地鏈接client.query.then(client.query.then(...))
,因為這會使我的代碼任意地縮進。 我寧願讓我的代碼盡可能平坦,並按順序執行這些調用,等待每個調用完成后再開始下一個調用。 我怎么做?
客戶端可能實際上並未解決會導致此行為的承諾。 如果您刪除所有 client.query,您將看到所有日志都將如您所願。 您的 Javascript 代碼已經在做您想做的事情,問題似乎出在 PG 客戶端上。
所以我能夠按照這個模式讓它在我的 ExpressJS 應用程序中工作。
本質上,您啟動了一個:
try{
client.query('BEGIN');
// ....do your sequential actions within here.
client.query('COMMIT');
}catch(e){
// handle error messaging here
client.query('ROLLBACK')
}
對於 ExpressJS,我將我的封裝在IIFE中(上面未顯示,但仍在某處的文檔中)。 所以上面的代碼看起來像這樣:
;(async() => {
//above code in here.
})()
.catch((e)=>{
//do the thing.
});
node-postgres 指南在這里。 我已經從下面的網站粘貼了片段。
const { Pool } = require('pg')
const pool = new Pool()
// note: we don't try/catch this because if connecting throws an exception
// we don't need to dispose of the client (it will be undefined)
const client = await pool.connect()
try {
await client.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES($1) RETURNING id'
const res = await client.query(queryText, ['brianc'])
const insertPhotoText = 'INSERT INTO photos(user_id, photo_url) VALUES ($1, $2)'
const insertPhotoValues = [res.rows[0].id, 's3.bucket.foo']
await client.query(insertPhotoText, insertPhotoValues)
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.