问题
I have a Lambda function to create snapshots in EC2. The function works but there is no return value (ie, I want to get this value data.SnapshotId
).
The EC2 call to create snapshot is nested inside a call to s3.getObject and before a call to s3.putObject.
s3.getObject(params, function(err, data) {
if (err) {
console.log(err);
console.log(message);
context.fail(message);
} else {
new aws.EC2().createSnapshot(params_snapshot, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data.SnapshotId); // this is my concern
}
});
var params_new = {
Bucket: bucket,
Key: key,
Body: body
};
s3.putObject(params_new, function(err, data) {
if (err) {
console.log(err);
console.log(message);
context.fail(message);
} else {
console.log('CONTENT TYPE putObject:', data.ContentType);
context.succeed(data.ContentType);
}
});
}
});
My primary concern is here
new aws.EC2().createSnapshot(params_snapshot, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data.SnapshotId); // this is my concern
}
});
回答1:
Try this:
s3.getObject(params, function(err, data) {
if (err) {
console.log(err);
console.log(message);
context.fail(message);
} else {
new aws.EC2().createSnapshot(params_snapshot, function(err, data) {
if (err) console.log(err, err.stack);
else {
console.log(data.SnapshotId);
}
var params_new = {
Bucket: bucket,
Key: key,
Body: body
};
s3.putObject(params_new, function(err, data) {
if (err) {
console.log(err);
console.log(message);
context.fail(message);
} else {
console.log('CONTENT TYPE putObject:', data.ContentType);
context.succeed(data.ContentType);
}
});
});
}
});
回答2:
The solution is I need to nest the s3.putObject() inside EC2() request because they happen concurrently.
s3.getObject(params, function(err, data) {
if (err) {
console.log(err);
console.log(message);
context.fail(message);
} else {
new aws.EC2().createSnapshot(params_snapshot, function(err, data) {
if (err) console.log(err, err.stack);
else {
console.log(data.SnapshotId);
var params_new = {
Bucket: bucket,
Key: key,
Body: body
};
s3.putObject(params_new, function(err, data) {
if (err) {
console.log(err);
console.log(message);
context.fail(message);
} else {
console.log('CONTENT TYPE putObject:', data.ContentType);
context.succeed(data.ContentType);
}
});
}
});
}
});
来源:https://stackoverflow.com/questions/34094233/aws-lambda-aws-ec2-doesnt-return-values-nodejs