我对Node JS Lamda函数还很陌生,还在学习。
我有一个函数,这里是TEST工作代码:
const https = require("https")
var url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"
exports.handler = async (event) => {
var variable_1 = "test 1"
var variable_2 = "test 2"
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify("Hello from Lambda!") + url,
}
return response
}
我需要在同一功能中执行两个操作。有可能有两个这样的导出处理程序吗?以及如何在另一个处理程序中使用一个处理过程中的变量?
const https = require("https")
var url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"
exports.handler = async (event) => {
var variable_1 = "test 1"
var variable_2 = "test 2"
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify("Hello from Lambda!") + url,
}
return response
}
//second handler - is this possible?
exports.handler = async (event) => {
var variable_3 = variable_1 + variable_2
// TODO implement
const response2 = {
statusCode: 200,
body:
JSON.stringify("Hello from Lambda - 2nd function!") + url + variable_3,
}
return response2
}
您所做的是创建多个导出函数,如下所示;
// First Function
exports.doSomethingA= async function() {
return something;
};
// Second Function
exports.doSomethingB= async function() {
return something;
};
想象一下,这两个函数在一个名为customer.js的文件中——你可以将该文件导入另一个文件中,并按如下方式调用该函数;
const customer = require('./customer');
exports.doSomethingC= async function() {
await customer.doSomethingA();
await customer.doSomethingB();
}
在你的情况下,我会有一个单独的文件,有两个功能。然后如上所述在处理程序中调用这些函数。别忘了导入。
您可以将variable1
和variable2
提升到更高的范围:
const https = require("https")
var url = "https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"
var variable_1 = "test 1" // moved to higher scope
var variable_2 = "test 2" // moved to higher scope
exports.handler1 = async (event) => {
// if you want to update variable1 and variable2 (optional)
// optional : if these variables need to change everytime handler1 is called; you can change them here.
variable1 = 'foo'
variable2 = 'bar'
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify("Hello from Lambda!") + url,
}
return response
}
//second handler - is this possible?
exports.handler2 = async (event) => {
var variable_3 = variable_1 + variable_2
// TODO implement
const response2 = {
statusCode: 200,
body:
JSON.stringify("Hello from Lambda - 2nd function!") + url + variable_3,
}
return response2
}
祝你好运。。。