Lambda函数MySQL结果在NodeJs 8.10上不起作用 [英] Lambda function MySQL result not working on NodeJs 8.10

查看:53
本文介绍了Lambda函数MySQL结果在NodeJs 8.10上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Node 6.10中有一个代码,它正在工作...但是,如果我将其转换为Node 8.10,它将无法正常工作

I have a code in Node 6.10 and it is working... But If I convert it to Node 8.10 it's not working

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查询并返回结果集,该方法也将无法正常工作.

Can some one please help me to detect the problem. It is also not working if I do the MySQL query in separate file and return the result set.

注意:如果我使用console.log(response)打印结果,而不是返回结果,显示正确的结果.

Note : If I print the result using console.log(response) instead returning it's showing the correct result.

推荐答案

问题是您正在从connection.query()回调函数中返回响应.这样,响应将返回回调函数的返回值,而不是外部Lambda函数的返回值.

The problem is that you are returning response from within the connection.query() callback function. That makes response the return value for the callback function, not the return value for the outer Lambda function.

重组代码的一种方法如下:

One way to restructure this code is as follows:

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}});
      }
    });
  });
};

这篇关于Lambda函数MySQL结果在NodeJs 8.10上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆