[英]node-mysql multiple statements in one query, execute conditionally on response from each
I want to execute multiple queries in one API call, but I only want to execute them conditionally based on the response of the previous one.我想在一个 API 调用中执行多个查询,但我只想根据前一个的响应有条件地执行它们。 How can I go about implementing this?我该如何去实施这个?
I've seen that I can do something like below to execute multiple queries.我已经看到我可以执行以下操作来执行多个查询。
connection.query('SELECT * ...; SELECT * ...', [1, 2], function(err, results) {
if (err) throw err;
});
But how do I await the response of the first before conditionally executing the second?但是如何在有条件地执行第二个之前等待第一个的响应?
That is not supported (unless written in database itself - like tsql, plsql or others).不支持(除非用数据库本身编写 - 如 tsql、plsql 或其他)。 What you can do - is execute query, wait for its results and then execute another accordingly.您可以做的是执行查询,等待其结果,然后相应地执行另一个。 example:例子:
const query1 = '.....';
connection.query(query1, [...params1], function(err, results) {
if (err) throw err;
const query2 = condition ? '....' : '........';
connection.query(query2, [...params2], ......);
});
and so on in and in (callback hell).等等(回调地狱)。
You can do it a bit better like that (i presume connection is: mysql.getConnection and is properly set without errors there).你可以像这样做得更好(我认为连接是:mysql.getConnection并且在那里正确设置没有错误)。 params<X>
is an array with parameters for the query. params<X>
是一个带有查询参数的数组。
const executeQuery = async (con, query, params) {
return new Promise((resolve, reject) => {
con.query(query, params, (err, result) => {
if (err) { return reject(err); }
return resolve(result);
});
});
}
mysql.getConnection((err, connection) => {
if (err) { throw err; }
try {
const query1 = '<some query>';
const result1 = await executeQuery(query1, params1);
const query2 = (condition on query1) ? '<query>' : '<other query>';
const result2 = await executeQuery(connection, query2, params2);
const query3 = (condition you want) ? '<query for that condition>' : '<or not>';
const result3 = await executeQuery(connection, query3, params3);
} catch (err) {
connection.release();
throw err;
} // if newest node you can use finally block and have only one connection.release();
connection.release();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.