node.js - 无法处理 alexa 意图
问题描述
我的代码没有运行,任何人都可以帮忙。无法说出文本,我可以返回处理程序输入响应吗?测试函数是一个 http 调用,可能需要 tieme。
function test(url, number)
{
return 5;
}
function speak(handlerInput) {
return handlerInput.responseBuilder
.getResponse();
}
const NumberFactIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'NumberFactIntent';
},
handle(handlerInput) {
const theNumber = handlerInput.requestEnvelope.request.intent.slots.number.value;
const repromptOutput = " Would you like another fact?";
const URL = "http://numbersapi.com";
test(URL, theNumber).then(function (data) {
console.log("data is " + data);
handlerInput.responseBuilder
.speak("Test Data")
.reprompt(repromptOutput)
return speak(handlerInput);
}).catch(function (data) {
console.log("error is " + data);
handlerInput.responseBuilder
.speak(`I wasn't able to find a fact for ${theNumber}` )
.reprompt(repromptOutput)
return speak(handlerInput);
});
}
};
解决方案
首先,您的test
函数不会返回承诺。我不知道这是否是故意的,你只是削减了 api 调用代码以使其更简单,但如果你想then
在它上面使用它应该返回一个 promise。
如果它在您的完整示例中返回一个承诺,那么您缺少的是在之前添加一个 return test
。你也应该handlerInput
从你的承诺中返回。代码应如下所示(我将删除一些不相关的代码):
const NumberFactIntentHandler = {
canHandle(handlerInput) {},
handle(handlerInput) {
const repromptOutput = " Would you like another fact?";
const URL = "http://numbersapi.com";
return test(URL, theNumber).then(function (data) {
return handlerInput.responseBuilder
.speak("Test Data")
.reprompt(repromptOutput)
}).catch(function (data) {
return handlerInput.responseBuilder
.speak(`I wasn't able to find a fact for ${theNumber}` )
.reprompt(repromptOutput)
});
}
};
现在您可能想知道为什么需要那些return
. 这是因为 JS 函数隐式返回undefined
,所以在这种情况下你必须明确告诉函数应该返回什么handle
。同样适用于 promise 的内部。
推荐阅读
- xcode - UISegmentedControl 不能再使用 IOS 13 Objective C 设置背景颜色
- laravel - Laravel 6 Backpack 4.0:如何在 FormRequest 类中获取当前页面 ID,或者我可以在不使用 FormRequest 类的情况下获得吗?
- visual-studio - 在 Visual Studio 2019 中将通用 Windows 应用程序导出为 EXE 文件
- git - 您是否应该提交 rc 和其他配置文件
- java - 在 libgdx 中保存和获取所有游戏对象
- python-3.x - 使用 fastAPI 将嵌套模式插入数据库?
- reactjs - 当 React 中的父状态更改时停止重新渲染子组件
- python - 在本地命名空间中编写代码比在 PyPy3 中的全局中慢
- excel - 在列中查找值并返回同一行但不同列的值
- excel - 使用 excel 计算下表所示的回报率