为什么在使用 SQL Server 和 express.js 的 res.send 时我的字典为空?

huangapple go评论69阅读模式
英文:

Why is my dictionary empty when using res.send with SQL Server and express.js?

问题

我正在使用mssql和express.js。我试图将recordset的结果设置为一个字典,然后使用res.send返回该字典,但字典是空的。我做错了什么?

这是我尝试过的内容:

app.post('/api/v1/test', async (req, res) => {
    tableNames = ["test", "test2"]

    var response = {};
    for (let index = 0; index < tableNames.length; index++) {
        const table = tableNames[index];
        let query = `SELECT * FROM ${table}`
        await queryDatabase(query, function(err, result){
            response[table] = result.recordset;
        });
    }

    res.send(
        {
            statusCode: 200,
            data: response
        }
    );
});
function queryDatabase(query, callback) {
    sql.connect(dbConfig, function (err) {
        if (err) {
            console.log(err);
        }
        var request = new sql.Request();
        request.query(query, function (err, result) {
            if (err) throw err
            callback(null, result)
        });
    });
}
英文:

I'm using mssql with express.js. I'm trying to set the recordset results into a dictionary and then returning that dictionary using res.send but dictionary is empty. What am I doing wrong?

Here's what I have tried:

app.post(&#39;/api/v1/test&#39;, async (req, res) =&gt; {
    tableNames = [&quot;test&quot;, &quot;test2&quot;]

    var response = {};
    for (let index = 0; index &lt; tableNames .length; index++) {
        const table = tableNames [index];
        let query = `SELECT * FROM ${table }`
        await queryDatabase(query , function(err, result){
            response[table ] = result.recordset;
        });
    }

    res.send(
        {
            statusCode: 200,
            data: response
        }
    );
});
function queryDatabase(query, callback) {
    sql.connect(dbConfig, function (err) {
        if (err) {
            console.log(err);
        }
        var request = new sql.Request();
        request.query(query, function (err, result) {
            if (err) throw err
            callback(null, result)
        });
    });
}

答案1

得分: 1

queryDatabase()函数不返回一个Promise,因此使用await对其没有实际作用,所以您的for循环不会在查询完成之前暂停,因此在response对象包含数据之前调用了res.send()

您可以选择切换到直接支持Promise的SQL模块,或者修改queryDatabase()以支持Promise,然后修改调用它的方式,如下所示:

app.post('/api/v1/test', async (req, res) => {
    try {
        tableNames = ["test", "test2"]

        var response = {};
        for (let table of tableNames) {
            const query = `SELECT * FROM ${table}`
            const result = await queryDatabase(query);
            response[table] = result.recordset;
        }

        res.send({ statusCode: 200, data: response });
    } catch (e) {
        console.error(e);
        res.status(500).send({ statusCode: 500, data: { error: "database error" } })
    }
});

function queryDatabase(query, callback) {
    return new Promise((resolve, reject) => {
        sql.connect(dbConfig, function (err) {
            if (err) {
                reject(err);
                return;
            }
            var request = new sql.Request();
            request.query(query, function (err, result) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(result);
            });
        });
    });
}
英文:

queryDatabase() does not return a promise and thus await does nothing useful with it so your for loop does not pause waiting for the query to complete and thus you call res.send() before your response object contains the data.

You can either switch to a sql module that directly supports promises or you can modify queryDatabase() to support promises and then modify how it's called to use the returned promise like this:

app.post(&#39;/api/v1/test&#39;, async (req, res) =&gt; {
    try {
        tableNames = [&quot;test&quot;, &quot;test2&quot;]

        var response = {};
        for (let table of tableNames) {
            const query = `SELECT * FROM ${table}`
            const result = await queryDatabase(query);
            response[table] = result.recordset;
        }

        res.send({ statusCode: 200, data: response });
    } catch (e) {
        console.error(e);
        res.status(500).send({ statusCode: 500, data: { error: &quot;database error&quot; } })
    }
});

function queryDatabase(query, callback) {
    return new Promise((resolve, reject) =&gt; {
        sql.connect(dbConfig, function (err) {
            if (err) {
                reject(err);
                return;
            }
            var request = new sql.Request();
            request.query(query, function (err, result) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(result);
            });
        });
    });
}

huangapple
  • 本文由 发表于 2023年5月25日 04:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定