按顺序执行多个数据库查询(承诺)
Execute Several database queries (promises) sequentially
数据库查询本身不是问题 - 它们工作正常。
问题是,我需要按顺序执行所有这些:
DELETE FROM myTable;
INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z);
SELECT * FROM myTable;
无论我尝试什么,我都不知道如何在 Node 中做到这一点。 seems to be the most-trafficked solution, and it would have me do something like this (where client
is from 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 (, , )", [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 客户端上。
数据库查询本身不是问题 - 它们工作正常。
问题是,我需要按顺序执行所有这些:
DELETE FROM myTable;
INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z);
SELECT * FROM myTable;
无论我尝试什么,我都不知道如何在 Node 中做到这一点。 client
is from 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 (, , )", [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 客户端上。