Nishant
Nishant

Reputation: 131

HelloWorld Alexa Skill - where does it start executing?

I'm learning javascript and the basics of building an Alexa Skill. Amazon provided a simple HelloWorld Alexa Skill found here: https://github.com/amzn/alexa-skills-kit-js/blob/master/samples/helloWorld/src/index.js

I have two questions about this function.

// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
    // Create an instance of the HelloWorld skill.
    var helloWorld = new HelloWorld();
    helloWorld.execute(event, context);
};
  1. Is this where the execution of the code starts when a user launches an Alexa Skill? It seems to me that this is the portion of the code that creates a HelloWorld object and starts the intent the user wants.
  2. Is this portion executed every time a user calls an intent? For example, if I asked Alexa "help" twice in this Alexa Skill, would this block of code be called twice? I'm coming from Java where there was a main method and still getting a grasp of javascript.

Upvotes: 0

Views: 270

Answers (1)

John Kelvie
John Kelvie

Reputation: 858

Yes, the function assigned to exports.handler is roughly equivalent to the Java main routine. The code inside this function will be executed every time the skill is called.

The code that is outside of it is also run, but only when the Lambda is first initialized, which happens infrequently unless your skill has very, very heavy usage. In the example below:

var globalCount = 0;
exports.handler = function (event, context) {
    var localCount = 0;
    // Create an instance of the HelloWorld skill.
    var helloWorld = new HelloWorld();
    helloWorld.execute(event, context);
    console.log("GlobalCount: " + globalCount + " LocalCount: " + localCount);
    localCount++;
    globalCount++;
};

You will see that globalCount keeps incrementing with each call to the skill - meaning only the function code is being called. The localCount meanwhile is re-initialized each time. So, the output will be:

GlobalCount: 0 LocalCount: 0
GlobalCount: 1 LocalCount: 0
GlobalCount: 2 LocalCount: 0

Hope that clarifies things!

Upvotes: 2

Related Questions