我有一个连接到Alexa技能的lambda函数。在技能的开始,我想将一个字符串存储到dynamoDB。因此我直接在启动请求中调用一个函数(该函数名为nameExport())。但是,如果我在启动请求中删除了“this.emit”命令,则该函数仅存储一些内容。如果我离开“this.emit”,该技能正在运行,但没有任何内容存储到数据库中。您可以在下面找到有关LaunchRequest的代码以及存储到dynamoDB中的函数。
var config = require("config");
var Alexa = require("alexa-sdk");
var AWS = require("aws-sdk");
var Speech = require("ssml-builder");
var dynamodb = new AWS.DynamoDB();
let handlers = {
'LaunchRequest': function () {
nameExport("testName");
let speech = new Speech ();
speech.say("Welcome by Emotions.")
speech.pause("100ms")
speech.say("Do you want to assess your current emotion?")
let speechOutput = speech.ssml(true);
this.emit(":ask", speechOutput)
},
'Emotion': function () {
let speech = new Speech();
...
应该将String写入数据库的nameExport函数:
function nameExport(name) {
var tableName = "myinfo";
dynamodb.putItem({
"TableName": tableName,
"Item": {
"name": {
"S": name
}
}
}, function(err, data) {
if (err) {
//context.fail('ERROR: Dynamo failed: ' + err);
} else {
console.log('Dynamo Success: ' + JSON.stringify(data, null, ' '));
//context.succeed('SUCCESS');
}
});
};
this.emit
刚刚完成lambda执行并且putItem
函数无法在其范围内完成。当this.emit
完成时你应该打电话给putItem
。
你可以通过使用async/await
来实现这一点(确保,lambda使用node.js v8.10):
'LaunchRequest': async function () {
await nameExport("testName");
let speech = new Speech ();
speech.say("Welcome by Emotions.")
speech.pause("100ms")
speech.say("Do you want to assess your current emotion?")
let speechOutput = speech.ssml(true);
this.emit(":ask", speechOutput)
},
async function nameExport(name) {
var tableName = "myinfo";
return new Promise((resolve, reject) => { dynamodb.putItem({
"TableName": tableName,
"Item": {
"name": {
"S": name
}
}
}, function(err, data) {
if (err) {
reject(err);
} else {
console.log('Dynamo Success: ' + JSON.stringify(data, null, ' '));
resolve();
}
})});
};
或者没有async/await
在回调中发出“:ask”,这不是那么温和的解决方案:
'LaunchRequest': function () {
let speech = new Speech ();
speech.say("Welcome by Emotions.")
speech.pause("100ms")
speech.say("Do you want to assess your current emotion?")
let speechOutput = speech.ssml(true);
nameExport("testName", () => this.emit(":ask", speechOutput));
},
function nameExport(name, callback) {
var tableName = "myinfo";
return new Promise((resolve, reject) => { dynamodb.putItem({
"TableName": tableName,
"Item": {
"name": {
"S": name
}
}
}, function(err, data) {
if (err) {
// some error handling
} else {
callback()
}
})});
};
顺便说一下 - 有一个Alexa SDK 2.0 - 1.0,你不想再使用它了。我建议切换到最新版本(通过重写代码或使用adapter)