我正在使用 nodejs和postgresqlDB 开发一个项目。 我想做的是,设置一个带有一些表的架构,这些表中也有彼此的外键。我实际解决方案中的问题是,每次启动应用程序时查询的顺序都不同。所以当它来的时候attributeTable是在架构之前创建的,从逻辑上讲是错误的。但是如何保存查询的顺序,以便按我想要的顺序创建表和架构?
我试图将相关表放在.then子句中,但是效果不佳。
function getDB(callback) {
let pgp = require('pg-promise')({
// Initialization Options
});
// fetches uri for queries
var dbPostgres = pgp(returnUriToDB());
// sql-queries in some constants
let createSchema = createSchema;
let attributeTable = createAttributeTable;
let objectGroupTable = createObjectGroupTable;
dbPostgres.query(createSchema)
.then(function () {
console.log('+++++ schema exists or was successfully created');
return;
})
.catch((err) => {
console.log(err);
console.log('----- schema could not be initialized :(');
return;
});
dbPostgres.query(attributeTable)
.then(function () {
console.log('+++++ attributeTable exists or was successfully created');
return;
})
.catch((err) => {
console.log(err);
console.log('attributeTable could not be initialized :(');
return;
});
dbPostgres.query(objectGroupTable)
.then(function () {
console.log('+++++ objectGroupTable exists or was successfully created');
return;
})
.catch((err) => {
console.log(err);
console.log('----- objectGroupTable could not be created :(');
return;
});
}
答案 0 :(得分:1)
这些调用dbPostgres.query
是异步的。检查承诺。
dbPostgres.query(createSchema)
.then(function() {
console.log('+++++ schema exists or was successfully created');
return;
})
.catch((err) => {
console.log(err);
console.log('----- schema could not be initialized :(');
return;
})
.then(dbPostgres.query(attributeTable))
.then(function() {
console.log('+++++ attributeTable exists or was successfully created');
return;
})
.catch((err) => {
console.log(err);
console.log('attributeTable could not be initialized :(');
return;
})
.then(dbPostgres.query(objectGroupTable))
.then(function() {
console.log('+++++ objectGroupTable exists or was successfully created');
return;
})
.catch((err) => {
console.log(err);
console.log('----- objectGroupTable could not be created :(');
return;
});
使用等待(更具可读性)
async function whatever() {
await dbPostgres.query(createSchema).catch((err) => {
console.log(err);
console.log('----- schema could not be initialized :(');
});
console.log('+++++ schema exists or was successfully created');
await dbPostgres.query(attributeTable).catch((err) => {
console.log(err);
console.log('attributeTable could not be initialized :(');
});
console.log('+++++ attributeTable exists or was successfully created');
await dbPostgres.query(objectGroupTable).catch((err) => {
console.log(err);
console.log('----- objectGroupTable could not be created :(');
return;
});
console.log('+++++ objectGroupTable exists or was successfully created');
}
// you can use async functions like promises (with then-catch schema)
whatever.then(..).catch(..).then(..);