Skip to content

Instantly share code, notes, and snippets.

@LouisAmon
Created March 16, 2018 08:46
Show Gist options
  • Save LouisAmon/2eb5ba96f8a69f8b9f1baf1def11169e to your computer and use it in GitHub Desktop.
Save LouisAmon/2eb5ba96f8a69f8b9f1baf1def11169e to your computer and use it in GitHub Desktop.
Fanout AWS Lambda
'use strict';
const aws = require('aws-sdk');
const lambda = new aws.Lambda({region: 'eu-west-1'});
const async = require('async');
exports.handler = (event, context, callback) => {
/*
Invokes a given Lambda function `event.function` in parallel for each given
argument `event.events`
Lambdas are invoked asynchronously and their results are gathered when the
last Lambda returns its values. Results are returned in the master Lambda.
*/
// Prepare tasks for parallel execution
var tasks = [];
event.events.forEach(function(item) {
var taskFunc = function(callback) {
var params = {
FunctionName: event.function,
InvocationType: "RequestResponse",
LogType: "None",
Payload: JSON.stringify(item)
};
lambda.invoke(params, function(err, data) {
if (err) {
// an error occurred
console.log(err, err.stack);
} else {
// successful response
var result = JSON.parse(data.Payload);
callback(null, result);
}
});
};
tasks.push(taskFunc);
});
// Run tasks in parallel
async.parallel(tasks, function(err, results) {
if (err) {
console.log(err);
} else {
callback(null, results)
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment