Here is an answer that is more idomatic for the latest JavaScript.
import AWS from 'aws-sdk';
const invokeLambda = (lambda, params) => new Promise((resolve, reject) => {
lambda.invoke(params, (error, data) => {
if (error) {
reject(error);
} else {
resolve(data);
}
});
});
const main = async () => {
// You shouldn't hard-code your keys in production!
// http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
AWS.config.update({
accessKeyId: 'AWSAccessKeyId',
secretAccessKey: 'AWSAccessKeySecret',
region: 'eu-west-1',
});
const lambda = new AWS.Lambda();
const params = {
FunctionName: 'my-lambda-function',
Payload: JSON.stringify({
'x': 1,
'y': 2,
'z': 3,
}),
};
const result = await invokeLambda(lambda, params);
console.log('Success!');
console.log(result);
};
main().catch(error => console.error(error));
Update
Rejoice! The AWS SDK now supports promises:
import AWS from 'aws-sdk';
const main = async () => {
// You shouldn't hard-code your keys in production!
// http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
AWS.config.update({
accessKeyId: 'AWSAccessKeyId',
secretAccessKey: 'AWSAccessKeySecret',
region: 'eu-west-1',
});
const params = {
FunctionName: 'my-lambda-function',
Payload: JSON.stringify({
'x': 1,
'y': 2,
'z': 3,
}),
};
const result = await (new AWS.Lambda().invoke(params).promise());
console.log('Success!');
console.log(result);
};
main().catch(error => console.error(error));