gpt4 book ai didi

node.js - Alexa 技能异步等待从 DynamoDB 获取数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:43 28 4
gpt4 key购买 nike

以下代码是我的 Alexa 技能中的启动处理程序,并且我的处理程序内部有一个名为 x 的变量。我试图将 x 设置为从 dynamoDB 获取的数据,并在 get 函数之外使用它(我从 https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.02 获取该函数),以便 Alexa 可以读出 x 的值(字符串)(如您在返回中看到的那样)。我的“get”函数中的语句不会更改 get 函数本身之外的 x 值。我知道 get 函数内部的 x 实际上正在更改,因为我将其记录到控制台。所以我就此发布了一篇类似的文章,我最初认为这是一个范围问题,但事实证明这是因为 get 函数是异步的。因此,我添加了 async 和 wait 关键字,如下所示。我是 NodeJS 的新手,所以根据我的研究,我认为我应该把它们放在哪里。但这仍然不起作用。

const LaunchHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === `LaunchRequest`;
},
async handle(handlerInput) {
var x;

//DYNAMO GET FUNCTION
await DBClient.get(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
x = data.Item.Answer;
} });

return handlerInput.responseBuilder
.speak(x)
.withShouldEndSession(false)
.getResponse();
},
};

顺便说一句,这是我(成功)从数据库返回的 JSON:

{
"Item": {
"Answer": "Sunny weather",
"Question": "What is the weather like today"
}
}

最佳答案

您正在寻找这样的东西吗?在句柄函数中,我调用另一个函数 getSpeechOutput 来创建一些反馈文本。因此函数调用dynamodb函数getGA来获取用户数据

const getSpeechOutput = async function (version) {
const gadata = await ga.getGA(gaQueryUsers, 'ga:users')

let speechOutput;
...
return ...
}

const UsersIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'UsersIntent';
},
async handle(handlerInput) {
try {
let speechOutput
...
speechOutput = await getSpeechOutput("long");
...

return handlerInput.responseBuilder
.speak(speechOutput)
.reprompt("Noch eine Frage?")
.withSimpleCard(defaulttext.SKILL_NAME, speechOutput)
.getResponse();

} catch (error) {
console.error(error);
}
},
};

这就是数据库函数:

const getUser = async function (userId) {
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Key: {
id: userId
}
}
return await dynamoDb.get(dynamodbParams).promise()
}

关于node.js - Alexa 技能异步等待从 DynamoDB 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192363/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com