[英]Returning AWS Lambda response before waiting for DB query - Serverless framework
I have a serverless framework node.js function that initializes mysql DB and then runs a query, ES6 is used to return an HTTP response at the end我有一个无服务器框架 node.js function 初始化 mysql DB 然后运行查询,ES6 用于最后返回 HTTP 响应
Is there a way to return the response before waiting for the DB call to finish, for example in node.js - res.send will return immediately and the function continues to run after the response is returned有没有办法在等待数据库调用完成之前返回响应,例如在 node.js - res.send 将立即返回并且 function 在返回响应后继续运行
Is there a better way to initialize a new mysql pool (perhaps reuse the pool instead of creating an ending it in each request?)有没有更好的方法来初始化一个新的 mysql 池(也许重用池而不是在每个请求中创建一个结尾?)
a: If for example the answer is to create the pool outside the function, how does it exactly work and how does the lambda function reuse it between requests, when does it get destroyed and how does it know when to recreate the pool a: 例如,如果答案是在 function 之外创建池,它是如何工作的,lambda function 如何在请求之间重用它,它何时被销毁以及它如何知道何时重新创建池
import mysql from "mysql";
export const myFunc = async (event) => {
try {
const pool = mysql.createPool({...}); // Creates a new mysql pool
await new Promise((resolve, reject) => {pool.query(
"INSERT STATEMENT", [...params], (error, results) => {
if(error) reject(error)
resolve(results)
}
)});
pool.end();
return {
statusCode: 200,
body: JSON.stringify({message: 'End'}),
};
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({message: 'Error'}),
};
}
};
- Is there a way to return the response before waiting for the DB call to finish
有没有办法在等待数据库调用完成之前返回响应
Yes, but then the Lambda will finish executing before waiting for DB call finishing.是的,但是 Lambda 将在等待数据库调用完成之前完成执行。 It will not guarantee that the call to DB will reach the DB, so it's not recommended to do so .
不保证对DB的调用一定会到达DB,所以不建议这样做。
If you absolutely need this, drop the await
statement in this line:如果您绝对需要这个,请在这一行中删除
await
语句:
From:从:
await new Promise((resolve, reject) => {pool.query(
To:到:
new Promise((resolve, reject) => {pool.query(
- Is there a better way to initialize a new mysql pool (perhaps reuse the pool instead of creating an ending it in each request?)
有没有更好的方法来初始化一个新的 mysql 池(也许重用池而不是在每个请求中创建一个结尾?)
Yes, you need to initialize your pool outside of Lambda handler.是的,您需要在 Lambda 处理程序之外初始化您的池。
Check out this article for more details:查看这篇文章了解更多详情:
https://dashbird.io/blog/leveraging-lambda-cache-for-serverless-cost-efficiency/ https://dashbird.io/blog/leveraging-lambda-cache-for-serverless-cost-efficiency/
Basically, you want to do instead of:基本上,您想做的不是:
import mysql from "mysql";
export const myFunc = async (event) => {
try {
const pool = mysql.createPool({...}); // Creates a new mysql pool
Do this:做这个:
import mysql from "MySQL";
const pool = mysql.createPool({...}); // Creates a new mysql pool
export const myFunc = async (event) => {
try {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.