Search code examples
javascriptaws-lambdaalexa-skills-kit

Different ways of writing the same alexa function


I've been working through Codecademy's alexa skills course, and the syntax of the lambda functions changed suddenly. Is there any difference between the following two lambda functions, and which should I use?

I've asked on the Codecademy forum with no response.

// First way
const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
  },
  handle(handlerInput) {
    return handlerInput.responseBuilder
      .speak("Hello, Welcome to Codecademy. What is your name?")
      .reprompt("Welcome. What is your name?")
      .getResponse();
  },
};
...
exports.handler = skillBuilder
  .addRequestHandlers(
    LaunchRequestHandler,
    ...
  )
  .lambda();
// Second way
var handlers = {
  'LaunchRequest': function() {
    this.response
        .speak("Hello, Welcome to Codecademy. What is your name?")
        .listen("Welcome. What is your name?");
    this.emit(':responseReady');
  },
...
}
...
exports.handler = function(event, context, callback){
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

Both variations run properly, but I mostly see code written the first way and the lessons are in the second format.


Solution

  • First one is written using alexa-sdk v2, while second one is written using alexa-sdk v1. They will work the same, the only difference is how the code is structured. v2 uses a bit different approach on the way the handler is chosen and has canHandle method to do that.

    If I would be you, I would work and build my skills with v2, because it is newer, it will have support for the latest features and in my opinion is better structured and more flexible than v1.