因此,我尝试使用以下代码从dynamodb中获取数据,但在调用查询函数后,我得到的是空值并且没有日志显示。
我在本地尝试过,它在本地运行,仅通过lambda函数不起作用,我还检查了我的角色是否具有读取dynamodb的权限,是否可以。所以我对此一无所知
"use strict";
const config = require("./config");
const AWS = require("aws-sdk");
AWS.config.update({
region: "us-east-1"
});
let dynamodb = new AWS.DynamoDB.DocumentClient({
region: "us-east-1"
});
var getAnswerToQuestion = (questionKey, callback) => {
var params = {
TableName: "genral-questions-db",
KeyConditionExpression: "#questionKey = :question",
ExpressionAttributeNames: {
"#questionKey": "question"
},
ExpressionAttributeValues: {
":question": String(questionKey)
}
};
console.log("Trying to query dynamodb");
dynamodb.query(params, (err, data) => {
if(err) {
console.log (err)
callback(err);
} else {
console.log(data.Items);
callback(data.Items[0]);
}
});
}
module.exports = {
getAnswerToQuestion
};
日志:
Function Logs:
START RequestId: 6adeddbe-4925-4877-a2c0-d20576145224 Version: $LATEST
2019-09-22T17:35:30.088Z 6adeddbe-4925-4877-a2c0-d20576145224 event.bot.name=bcbsri
2019-09-22T17:35:30.088Z 6adeddbe-4925-4877-a2c0-d20576145224 dispatch userId=pn6yexoq87uej2evt9huhilc5f99bhb7, intentName=GenralQuestionIntent
2019-09-22T17:35:30.088Z 6adeddbe-4925-4877-a2c0-d20576145224 GenralQuestionIntent was called - Srinivas
2019-09-22T17:35:30.089Z 6adeddbe-4925-4877-a2c0-d20576145224 have to query the db hsa
2019-09-22T17:35:30.089Z 6adeddbe-4925-4877-a2c0-d20576145224 Trying to query dynamodb
END RequestId: 6adeddbe-4925-4877-a2c0-d20576145224
REPORT RequestId: 6adeddbe-4925-4877-a2c0-d20576145224 Duration: 596.83 ms Billed Duration: 600 ms Memory Size: 128 MB Max Memory Used: 76 MB Init Duration: 193.27 ms
甚至没有出错,只是不返回任何数据。请帮助我解决此问题
编辑: 这是我尝试调用utils方法(db)的代码
module.exports = function(intentRequest) {
return new Promise((resolve, reject) => {
// Resolve question key
const questionKey = intentRequest.currentIntent.slots.QuestionKey;
let speechText;
console.log('have to query the db', questionKey);
utils.getAnswerToQuestion(questionKey, res => {
if(res ) {
speechText = res.answer;
} else {
speechText = "Sorry, details about " + questionKey + " was not found";
}
const response = {
fullfilmentState: 'Fulfilled',
message: { contentType: 'PlainText', content: speechText }
};
console.log(response);
resolve(response);
return lexResponses.close(intentRequest.sessionAttributes, response.fullfilmentState, response.message);
});
});
};
答案 0 :(得分:2)
我敢打赌,这是人们将Node.js与Lambda一起使用时最常见的问题。
当Node.js Lambda到达主线程的末尾时,它将结束所有其他线程。当到达处理程序的末尾时,它将停止所有正在运行的并发Promise或异步调用。
要确保lambda不会过早终止那些线程,请使用await
等到这些承诺完成。
在您的情况下,对任何AWS请求都使用.promise()
方法,然后对它们进行await
:
try {
const data = await dynamodb.query(params).promise();
console.log(data.Items);
callback(data.Items[0]);
} catch (err) {
console.log(err);
callback(err);
}