首页 > 解决方案 > 从 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;
    });
}

期望的结果是它在第二部分之前执行第一部分,因为第二部分需要第一部分的结果。

标签: javascriptsqlnode.js

解决方案


尝试删除外括号,以便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;
    });
}

推荐阅读