【发布时间】:2021-10-26 17:58:32
【问题描述】:
我想编写一个嵌套回调 JavaScript,以便在不同的 SQL 表中使用 INSERT 语句的后续 ID。我的代码如下所示:
db.promise().query(
// create Place with auto-generated PlaceID
`INSERT INTO Place (Street,PLZ) VALUES('${street}', ${plz})`
,
(err,result) => {
db.promise().query(
// insert User using PlaceID
`INSERT INTO User (PlaceID, Name, Created_On) VALUES(${result.insertID}, '${name}',current_timestamp())`
,
(err,result) => {
// insert Account using UserID
`INSERT INTO Account (UserID, Email, Password, Created_On) VALUES(${result.insertID}, '${email}', '${pwd}', current_timestamp())`
}
);
}
);
但是,当尝试使用 Node.js 运行它时,它会显示 Error: Callback function is not available with promise clients。
您是否有解决方案来检索以下 INSERTS 的插入 ID?
我也尝试过.then((result)=>{..}),这似乎可行,但结果。插入ID 始终未定义?
// create place with auto-generated PlaceID
db.promise().query(`INSERT INTO Place (Street,PLZ) VALUES('${strasse}', ${plz})`)
.then((err,result) => {
if(err)throw err;
// insert User using PlaceID
db.promise().query(
`INSERT INTO User (PlaceID, Name, Created_On) VALUES(${result.insertID}, '${name}',current_timestamp())`)
.then((err,result) => {
if(err)throw err;
// insert Account using UserID
db.promise().query(`INSERT INTO Account (UserID, Email, Password, Created_On) VALUES(${result.insertID}, '${email}', '${pwd}', current_timestamp())`)
});
}).catch((err)=>{console.log(err)});
【问题讨论】:
-
你为什么用
db.promise().query()而不是db.query()? -
您使用
.then((result) => ...)处理承诺的结果。 -
@Barmar 当我在没有 promise() 的情况下执行此操作时,它表示 HTTP 标头是在客户端之前设置的。我尝试使用
.then((result) =>..)但这给了我一个 nhandledPromiseRejectionWarning
标签: javascript sql node.js promise callback