如何在Node.js / AWS Lambda中使用我的函数

时间:2018-10-25 09:09:04

标签: aws-lambda

我正在基于Node.js创建一个AWS Lambda函数。在此函数(函数A)中,除其他功能外,我需要调用另一个lambda函数(函数B)。

我进行了一个测试lambda函数(函数C)的测试,该函数只处理对函数B的调用:

var aws = require('aws-sdk');
var lambda = new aws.Lambda;
exports.handler = function(event, context, callback) {
lambda.invoke({
  FunctionName: 'dynamoCatego',
  Payload: '{ "catid": "40000000"}'
}, function(err, data){
  if(err){console.log(err, err.stack);} // an error occurred
  else {callback(null, JSON.parse(data.Payload));} // successful response
}
)};

它工作得很好,我从函数中得到了想要的结果。

现在,我想将这段代码内联到函数A中,并且通常具有一个变量(typeA),该变量等于调用结果(对于提供的有效负载)。而且我被困在这里...

我尝试将代码片段复制/粘贴到main函数中。无法检索结果,则创建的变量根本没有值。

我想我需要做的是在lambda函数的根目录中定义子函数,并在需要时用特定的有效负载调用它。

如果有人能引导我朝正确的方向前进,我将非常感激

1 个答案:

答案 0 :(得分:0)

这是在另一个lambda处理程序中包装远程lambda函数的示例:

const aws = require('aws-sdk');
const lambda = new aws.Lambda();

// this is a specific lambda function wrapper,
// you could make it more general if needed.
// (i.e. make FunctionName the first argument.
async function dynamoCatego(args) {
  const FunctionName = 'dynamoCatego';
  const Payload = JSON.parse(args);
  // use .promise() to return a promise that can be awaited,
  // rather than deal with nested callbacks:
  const data = await lambda.invoke({ FunctionName, Payload }).promise();
  // n.b. this will just throw if there's an error,
  // so you may choose to try, catch it.
  return JSON.parse(data.Payload || 'null');
  // (Payload will be undefined if nothing is returned, but JSON.parse(undefined) is an error
}

exports.handler = async function handler(event, context, callback) {
  // other things...
  const result = await dynamoCatego({ catid: '40000000' });
  // other things...
  callback(null, result);
}

请注意,使用async / await意味着您将需要使用Node 8.10(AWS也为您提供了6.10的选项,但是除了旧项目之外,几乎没有理由使用旧版本)。相反,您可以使用嵌套回调进行此操作,但我认为这种方法更具可读性。

但是,如果您真的要使用回调,则可以这样做:

const Aws = require('aws-sdk');
const lambda = new Aws.Lambda();

function dynamoCatego(args, cb) {
  const FunctionName = 'dynamoCatego';
  const Payload = JSON.parse(args);
  lambda.invoke({ FunctionName, Payload }, (err, data) => {
    if (err) { throw err; }
    const result = JSON.parse(data.Payload);
    cb(result);
  });
}

exports.handler = function handler(event, context, callback) {
  // other things...
  dynamoCatego({ catid: '40000000' }, (result) => {
    // do things with the result...
    callback(null, result);
  });
 }