因为以前没有nodejs使用经验 所以刚开始使用nodejs写lambda的时候因不知道nodejs的异步特性导致经常无法获得response
善用asyn和await,以下是示例:
async function getReport(airline) {
var params = {
TableName: tableName,
IndexName:"type-airline-index",
KeyConditionExpression: "#type = :type and #airline = :airline",
ExpressionAttributeNames:{
"#type": "type",
"#airline": "airline"
},
ExpressionAttributeValues: {
":type":"report",
":airline":airline
},
};
let result;
try {
result = await docClient.query(params).promise();
}
catch(err) {
return {
body:err
};
}
if(result.Count == 0){
return '';
}
return result.Items;
}
另外在调用函数的时也需要使用await
var ANAData = await dynamodb_Function.getReport("ANA");
ps:不同页面的nodejs的函数需要export后才能调用 如:module.exports = {getReport};