javascript - 从 SQL 获取结果时函数乱序
问题描述
当现有 SQL 记录存在时,我想使用它而不是添加另一个记录,但如果它还不存在,我想添加它。我遇到的问题是,当我的 Node.js 应用程序的端点被调用时,它没有以正确的顺序执行,因此在我检查它的长度以查看是否需要添加新记录之后,会进行 SQL 查找以查找现有记录。
// it does this second
let existingGet = "SELECT * FROM Items WHERE name = '" + productName + "'";
let existingItem = async () => {
db.query(existingGet, function (err, rows, fields) {
return rows;
});
};
// it does this first
if (await existingItem().length > 0) {
// Existing found, use existing
itemId = existingItem.ID;
} else {
// Item not found, create new
var sql = "INSERT INTO Items (...) VALUES (...)";
await db.query(sql, async function (err, result) {
itemId = existingItem.affectedRows.ID;
});
}
期望的结果是它在第二部分之前执行第一部分,因为第二部分需要第一部分的结果。
解决方案
尝试删除外括号,以便existingItem
从查询中接收结果
// it does this second
let existingGet = "SELECT * FROM Items WHERE name = '" + productName + "'";
//removed outer brackets
let existingItem = async () =>
db.query(existingGet, function (err, rows, fields) {
return rows;
});
// it does this first
if (await existingItem().length > 0) {
// Existing found, use existing
itemId = existingItem.ID;
} else {
// Item not found, create new
var sql = "INSERT INTO Items (...) VALUES (...)";
await db.query(sql, async function (err, result) {
itemId = existingItem.affectedRows.ID;
});
}
推荐阅读
- c# - 在 C# asp.net core 2.1 中通过用户名和密码在 MQTT 服务器上对 MQTT 客户端进行身份验证
- excel - 数据输入表上的强制性字段检查
- javascript - 编写此代码的更简洁的方法[限制字符]
- javascript - 图像 (SandTimer) 动画 - HTML、CSS、Javascript
- c++ - C++ 标准是否允许未初始化的 bool 使程序崩溃?
- python - 当表格单元格为混合格式时,抓取维基百科信息框
- css - Safari 手机上的 React 应用程序扩展超过 100%
- python - 有什么方法可以在不使用 Python 中的任何字符串或数字的情况下打印一些东西?
- python - 秩 0 张量的输入层初始化 Keras
- unit-testing - @WithMockUser 未进行身份验证