首页 > 解决方案 > 无法处理 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);
        }); 
    }
};

标签: node.jspromisealexaalexa-appalexa-sdk-nodejs

解决方案


首先,您的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 的内部。


推荐阅读