Alexa请求技能构建者不等待响应构建者

时间:2018-08-14 06:27:18

标签: node.js aws-lambda alexa alexa-skills-kit

我已经创建了Alexa技能,该技能需要从API提取数据。

在示例aws-nodejs-factskill之后,我创建了技能:

exports.handler = async function (event, context) {
    console.log(`REQUEST++++${JSON.stringify(event)}`);
    if (!skill) {
        skill = Alexa.SkillBuilders.custom()
            .addRequestHandlers(
                customHandler,
                HelpHandler,
                ExitHandler,
                FallbackHandler,
                SessionEndedRequestHandler,
            )
            .addErrorHandlers(ErrorHandler)
            .create();
    }

    return skill.invoke(event, context);
};

const customHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'LaunchRequest'
            || (request.type === 'IntentRequest'
                && request.intent.name === 'customIntent');
    },
    handle(handlerInput) {

        const myRequest = "size=1&lat=<lat>&long=<lon>";
        var speechOutput = "Default Message";
        callAPI(myRequest, (myResult) => {
            console.log("sent     : " + myRequest);
            console.log("received : " + JSON.stringify(myResult));

            speechOutput = JSON.stringify(myResult).replace(/['"]+/g, '');

            return handlerInput.responseBuilder
                .speak(speechOutput)
                .withSimpleCard(SKILL_NAME, speechOutput)
                .getResponse();
        });
    },
};

但是返回到Alexa的响应为空,并且会话以错误结束。

{
"body": {
    "version": "1.0",
    "response": {},
    "sessionAttributes": {},
    "userAgent": "ask-node/2.0.7 Node/v8.10.0"
}

Lambda

Session ended with reason: ERROR

API调用的响应很好。而且我可以在控制台中看到响应。

如果我使用相同的代码并在外部返回构建器,则可以正常工作。

const customHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'LaunchRequest'
            || (request.type === 'IntentRequest'
                && request.intent.name === 'customIntent');
    },
    handle(handlerInput) {

        const myRequest = "size=1&lat=<lat>&long=<lon>";
        var speechOutput = "Default Message";
        locateNearestDealer(myRequest, (myResult) => {
            console.log("sent     : " + myRequest);
            console.log("received : " + JSON.stringify(myResult));

            speechOutput = JSON.stringify(myResult).replace(/['"]+/g, '');
        });

        return handlerInput.responseBuilder
          .speak(speechOutput)
          .withSimpleCard(SKILL_NAME, speechOutput)
          .getResponse();
    },
};

我到底在做什么错,我该如何解决?

1 个答案:

答案 0 :(得分:0)

您应将handle函数设置为异步函数,因为它需要等待api响应,这是一个示例:

const HelloWorldIntentHandler = {
canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
        && Alexa.getIntentName(handlerInput.requestEnvelope) === 'HelloWorldIntent';
},
async handle(handlerInput) {
const response = await httpGet();
return handlerInput.responseBuilder
        .speak('Example')
        .getResponse();
}}

function httpGet() {
  return new Promise((resolve, reject) => {
  request.get(URL, (error, response, body) => {
    console.log('error:', error); 
    console.log('statusCode:', response.statusCode);
    resolve(JSON.parse(body));
  });
});
}