问题描述
到目前为止,我的代码是这样的:
const AWS = require('aws-sdk');
AWS.config.update({ region: 'eu-west-1' });
const CF = new AWS.CloudFormation({ apiVersion: '2010-05-15' });
const updateParams = {
StackName: myStackName,UsePrevIoUstemplate: true,Parameters: [
{
ParameterKey: "StackOffline",ParameterValue: "Online"
}
],Capabilities: [
"CAPABILITY_IAM","CAPABILITY_AUTO_EXPAND"
]
};
exports.handler = async (event) => {
CF.updateStack(updateParams,(err,data) => {
if (err)
console.log(err,err.stack);
else
console.log(data);
});
// ...
};
问题是……它什么也没做。当它运行时,它实际上不记录任何东西;不是 data
,也不是错误消息。
我尝试同时使用堆栈名称和唯一堆栈 ID,但都没有奏效。
最后,我保存了 Request
的返回值(我认为是 updateStack()
),这是它的 response
属性:
response: Response {
request: [Circular *1],data: null,error: null,retryCount: 0,redirectCount: 0,httpResponse: HttpResponse {
statusCode: undefined,headers: {},body: undefined,streaming: false,stream: null,_abortCallback: [Function: callNextListener]
},maxRetries: 3,maxRedirects: 10
}
(如果需要,我也可以发布整个 Request
。我没有发布,因为它很大,而且我不知道它是否包含任何敏感信息。)
我认为这些 null
值是一个问题。我哪里出错了?
解决方法
您遇到了古老的 async/await
和 callback
问题。 TLDR;不要合并它们。
AWS Lambda function handler in Node.js
对于非异步处理程序,函数继续执行,直到事件循环为空或函数超时。在所有事件循环任务完成之前,不会将响应发送给调用者。如果函数超时,则会返回错误。您可以通过将 context.callbackWaitsForEmptyEventLoop 设置为 false 来配置运行时立即发送响应。
把你的代码改成这样:
const AWS = require('aws-sdk');
AWS.config.update({ region: 'eu-west-1' });
const CF = new AWS.CloudFormation({ apiVersion: '2010-05-15' });
const updateParams = {
StackName: myStackName,UsePreviousTemplate: true,Parameters: [
{
ParameterKey: "StackOffline",ParameterValue: "Online"
}
],Capabilities: [
"CAPABILITY_IAM","CAPABILITY_AUTO_EXPAND"
]
};
exports.handler = async (event) => {
try {
const data = await CF.updateStack(updateParams).promise();
console.log(data);
// ...
}
catch (err) {
console.log(err,err.stack);
}
};