【问题标题】:Outside function not calling in lambda node js exports.handler?外部函数未在 lambda 节点 js export.handler 中调用?
【发布时间】:2021-06-17 11:14:49
【问题描述】:

在lambda中我们写node js脚本时,是否可以在exports.handler之外运行函数?

例如:

// index.js

const main = async () => {

console.log(" running ");
};
main();
exports.handler = function(event, context) {
 const response = {
    statusCode: 200,
    body: JSON.stringify('done!'),
  };
return response;
};

如果我需要在 lambda 中运行 index.js,它只在 exports.handler 的函数内部执行。 它没有执行exports.handler 之外的“主要”功能。请帮助某人

【问题讨论】:

  • 如果要调用main()函数,可以从exports.handler函数中调用。您正在努力实现的目标可能有助于给出更好的答案。
  • 实际上,在主函数中,我有逻辑连接 mongo db...当主函数尝试连接时,处理程序中的函数也在运行。及其失败

标签: node.js aws-lambda


【解决方案1】:

从您的问题和评论看来,您正在寻找一种方法来运行连接到 MongoDB 的函数,但不是每次调用 lambda 函数时都重新运行连接。

解决此问题的一种方法是将数据库连接缓存在外部范围内的变量中。

// Store db after first connection
let cachedDb = null;
// database connection function
const main = async () => {
  // Guard clause to return cache
  if (cachedDb) return cachedDb;
  
  // Only creates the connection on the first function call
  const client = await MongoClient.connect('your connection URI')
  const db = await client.db('your database')
  cachedDb = db;
  
  return db;
};

exports.handler = async (event, context) => {
  const db = await main();
  // Add database interactions/queries
  // ...

  const response = {
    statusCode: 200,
    body: JSON.stringify('done!'),
  };
return response;
};

【讨论】:

  • 我在 python 中使用相同的示例,但在分配之前给出了局部变量。对于缓存数据库
猜你喜欢
  • 1970-01-01
  • 2020-10-16
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
相关资源
最近更新 更多