我在Node 6.10中有一个代码,它正在工作... 但是如果我将其转换为Node 8.10,它将无法正常工作
var mysql = require("mysql");
var connection = mysql.createConnection({
host: " localhost",
user: "root",
password: "",
database: "parser_db"
});
exports.handler = async event => {
connection.connect();
let response = {
statusCode: 400,
body: { Method: "Invalid", event }
};
var readTable = "SELECT * FROM documents where id = " + mysql.escape(1);
connection.query(readTable, function(err, results, fields) {
if (err) throw err;
else {
response = {
statusCode: 200,
body: { results }
//body: { results }
};
console.log(response);
return response;
}
});
};
有人可以帮我发现问题吗?如果我在单独的文件中执行MySQL查询并返回结果集,它也将无法正常工作。
注意:如果我使用console.log(response)打印结果,而不是返回结果 显示正确的结果。
答案 0 :(得分:1)
问题是您正在从connection.query()回调函数中返回响应。这样,响应将返回回调函数的返回值,而不是外部Lambda函数的返回值。
重构此代码的一种方法如下:
exports.handler = async (event) => {
connection.connect();
return new Promise((resolve, reject) => {
const readTable = `SELECT * FROM documents where id = ${mysql.escape(1)}`;
connection.query(readTable, (err, results, fields) => {
if (err) {
reject(err);
} else {
resolve({statusCode: 200, body: {results}});
}
});
});
};
答案 1 :(得分:1)
除了@jarmod的答案外,您还可以使用util.promisify方法来简化connection.query
,以便可以使用await
关键字来简化代码
const util = require('util');
exports.handler = async (event) => {
connection.connect();
const readTable = `SELECT * FROM documents where id = ${mysql.escape(1)}`;
const connQueryPromisified = util.promisify(connection.query).bind(connection);
const result = await connQueryPromisified(readTable);
return {statusCode: 200, body: {results}};
};