Alexa SDK:在https响应中保存sessionAttributes

时间:2019-05-25 13:23:24

标签: alexa-skills-kit

我有技巧,我想从url加载一些数据并将其存储在SessionAttributes中。

所以我将此写到了handle(handlerInput)的{​​{1}}中:

LaunchRequestHandler

日志向我显示了正确的对象,但是当我尝试在下一个意图中加载sessionAttributes时,它为空。我假设它与响应函数中的setSessionAttributes有关,因为如果我在此代码后直接设置某些内容,它将起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这可能是由于异步操作所致。请使用async / await进行API调用,然后保存。示例示例,

const getData = () => {
  return new Promise((resolve, reject) => {
    require("https").get(url, resp => {
      resp.on("data", chunk => {
        data += chunk;
      });

      resp.on("end", () => {
        resolve(data);
      });
    });
  });
};

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === "LaunchRequest";
  },
  async handle(handlerInput) {
    const speechText = "welcome";
    const data = await getData(); //asynchronous operation
    const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
    sessionAttributes.data = data;
    handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .withSimpleCard("Welcome to the Skill", speechText)
      .getResponse();
  }
};