Returning handler.ResponseBuilder from promise.then() method

空扰寡人 提交于 2019-12-05 19:02:38

The error you're seeing is because NodeJS and the Alexa SDK are asynchronous. As you can read from the Alexa SDK code, it invokes your request handlers and expects a Promise back. In your example, as your code does not return anything explicitly after calling rcvPromise.then, an empty response is sent back, and the SDK sends an empty response to Alexa, causing the error. When your then() function will be executed, the Alexa response has already been sent and your handlerInput.responseBuilder result is ignored.

To solve this problem, you have two solutions:

a/ you can insert a return statement before rcvPromise.then, such as

return rcvPromise.then(function(speechText) {
   console.log('rcv Promise resolved with ',speechText);
     return handlerInput.responseBuilder
       .speak(speechText) 
       .withSimpleCard('skill_name', speechText) 
       .withShouldEndSession(false)
       .getResponse();
 });   

This way, your handler will return a Promise to the SDK and the SDK will use the result of the promise to build the response to send to Alexa.

b/ If you are using NodeJS 8, you can use the new await/async syntax. Under the hood, it is the same as the above solution, but it will make the code easier to read.

var speechText = await receiveMsgQ();
console.log('rcv Promise resolved with ',speechText);
return handlerInput.responseBuilder
       .speak(speechText) 
       .withSimpleCard('skill_name', speechText) 
       .withShouldEndSession(false)
       .getResponse();

Note that your entire handler function must be marked as async for this to work. Read more about async and await at https://blog.risingstack.com/mastering-async-await-in-nodejs/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!