13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LambdaからLambdaを並列で呼び出す方法(node)

Last updated at Posted at 2018-09-27

はじめに

lambdaからlambdaを並列で呼び出し、かついい感じに子lambdaからステータスを受け取って親lambdaが返却するやり方を知りたかったが、google先生に聞くとStepFunctionばかり出てくるのでまとめた。

image.png

こたえ

async使えばいけるぞ

parallel.js
var async = require('async');
const AWS = require('aws-sdk');
var lambda = new AWS.Lambda();

function callParallelLambda(arg) {
	return function(callback2) {
		var payload = {
			key: 'key' + arg.id,
		}
		//子lambdaへのリクエストパラメータは文字列で渡す
		payload = JSON.stringify(payload);
		var params = {
			FunctionName: 'childelambda', // 子lambdaの名前。
			InvocationType: "RequestResponse", // 子lambdaの呼び方。レスポンス受けたいので同期で呼ぶ。
			Payload: payload // 子lambdaへのリクエストパラメータ
		};
		lambda.invoke(params, function (err, data) {
			// if elseでcallbackしないと、"既にcallbackが呼ばれているぞ"というエラーになる
			if (err) {
				callback2(null, err)
			} else {
				const response = {
					statusCode: 200,
					headers: {},
					body: { "message": "呼び出せました", "data": data }
				};
				callback2(null, response)
			}
		});

	}
}

exports.handler = (event, context, callback) => {
	// コールバック関数の配列を作成
	var callbacks = []
	for (var i = 0; i < 5; ++i) {
		console.log(i)
		callbacks.push(callParallelLambda(i));
	}

	async.parallel(callbacks, function (err, results) {
		console.log('error = ' + err);
		console.log('results = ' + results);
		callback(null, results);
	});
}

注意点

13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?