我是Node.js和Javascript的新手,正在使用Lambda函数和DynamoDB开发Alexa应用程序。 我在DynamoDB中有一个名为:与PrimaryKey聊天的表:'Said'和一个列'say'。每当启动Alexa技能时,我只想根据用户说的内容获取记录并返回。所以它基本上是一个主键上的查询工作正常。 但是,我没有从语音输出变量中的lambda函数得到任何响应,因为API不等待响应构建器完成对DynamoDB的异步调用并返回空响应。 有没有办法在发送响应之前强制执行异步调用?
const WelcomeMessage = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest' ||
(request.type === 'IntentRequest');
},
handle(handlerInput) {
var ans;
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({
region: 'us-east-1'
});
// Create the DynamoDB service object
var dynamodb = new AWS.DynamoDB();
var params = {
TableName: 'chat',
Key: {
'said': {
S: 'Hi Sir' + ''
}
},
ProjectionExpression: 'say'
};
dynamodb.getItem(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
if (data) {
return handlerInput.responseBuilder
.speak(data.Item.say.S + '')
.getResponse();
} else {
ans = 'You dint train me for that!';
return handlerInput.responseBuilder
.speak(ans)
.getResponse();
}
}
});
}
};
输出错误:
我找到了一个解决方法。我返回一个promise并在返回之前解决它,确保在发送响应之前完成回调。
const WelcomeMessage = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest');
},
handle(handlerInput) {
return new Promise((resolve) => {
var ans;
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-1'});
// Create the DynamoDB service object
//ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'});
var dynamodb = new AWS.DynamoDB();
var params = {
TableName : 'chat',
Key: {
'said':{S: handlerInput.requestEnvelope.request.intent.slots.input.value+''}
}
};
dynamodb.getItem(params, function(err, data) {
if (err){
console.log(err, err.stack);
}
else{
if(data.Item){
return resolve(handlerInput.responseBuilder
.speak(data.Item.say.S+'')
.withShouldEndSession(false)
.getResponse());
}
else{
ans='You dint train me for that!';
return resolve(handlerInput.responseBuilder
.speak(ans)
.withShouldEndSession(false)
.getResponse());
}
}
});
});
}
};