首页 文章

Lambda函数不返回对Alexa技能的响应

提问于
浏览
0

我有一个用于Alexa技能的Lambda函数,该函数用Nodejs编写 . 它对服务进行HTTP调用,并将输出返回给Alexa技能 . 调用技能时,将调用lambda,并进行HTTP调用 . 但是,在返回HTTP响应之前,lambda返回,因此技能无法得到答案 .

以下是我的Lambda函数

var Alexa = require('ask-sdk');
var http = require('http');
var SKILL_NAME = 'Some Facts';

var GetNewFactHandler = {
  canHandle(handlerInput) {
  var request = handlerInput.requestEnvelope.request;
  return request.type === 'LaunchRequest'
  || (request.type === 'IntentRequest'
    && request.intent.name === 'GetNewFactIntent');
},
handle(handlerInput) {
    getTop("", (data)=>{
    let speechOutput = "The result is " + data;
        console.log("resp from lambda ", speechOutput)
        var respSpeak =  handlerInput.responseBuilder
        .speak(speechOutput)
        .withSimpleCard(SKILL_NAME, data)
        .getResponse();
        console.log("respSpeak ", respSpeak);
        return respSpeak;
    });
  },
};


function getTop(query, callback) {
   var options = {
        host: 'somehost',
        port: '8100',
        path: '/top',
        method: 'GET',
   };

    var req = http.request(options, res => {
        res.setEncoding('utf8');
        var responseString = "";

        res.on('data', chunk => {
            responseString = responseString + chunk;
        });

        res.on('end', () => {
            console.log("********",JSON.parse(responseString).Name);
            let respStr = JSON.parse(responseString).Name;
            callback(respStr);
        });

    });
    req.end();
}

在lambda日志中,我可以在getTop()中看到日志 . 但是,在收到HTTP调用的响应之前,lambda的响应会返回 . 我认为在回调中构建响应将确保仅在HTTP调用完成后才返回响应 . 但事实似乎并非如此 . 怎么解决这个问题?任何帮助表示赞赏 .

1 回答

  • 3

    默认情况下,Node.js为 asynchronous ,这意味着在服务返回数据之前调用响应构建器 . 我在调用客户资料api获取电话号码时遇到了类似问题,我使用 async-await 解决了这个问题

    async handle(handlerInput) {
        const { serviceClientFactory, responseBuilder } = handlerInput;
        try {
          const upsServiceClient = serviceClientFactory.getUpsServiceClient();
          const profileMobileObject = await upsServiceClient.getProfileMobileNumber();
         
          const profileMobile = profileMobileObject.phoneNumber;
          const speechResponse = `Hello your mobile number is, ${profileMobile}</say-as>`;
          const cardResponse = `Hello your mobile number is, ${profileMobile}`
          return responseBuilder
                          .speak(speechResponse)
                          .withSimpleCard(APP_NAME, cardResponse)
                          .getResponse();
        } catch (error) {
          console.log(JSON.stringify(error));
          if (error.statusCode == 403) {
            return responseBuilder
            .speak(messages.NOTIFY_MISSING_PERMISSIONS)
            .withAskForPermissionsConsentCard([MOBILE_PERMISSION])
            .getResponse();
          }
          console.log(JSON.stringify(error));
          const response = responseBuilder.speak(messages.ERROR).getResponse();
          return response;
        }
      },
    

    在调用 service 之前使函数 async 并使用 await ..您也可以通过 Promises 执行此操作

相关问题