0

I am trying to pass on an array of strings from the 'LaunchRequest' to the 'TellAJoke' intent.

My problem is that this.attributes['joke'] is always undefined in the 'TellAJoke' function.

'LaunchRequest': function() {
    var url = "https://www.reddit.com/r/jokes/top.json?limit=1";
    var self = this;

    var request = https.get(url, function(res) {
        var body = '';
        res.on('data', function(chunk){
            body += chunk;
        });
        res.on('end', function(){
            var redditResponse  = JSON.parse(body);
            redditResponse['data'].children.forEach(function(child) {
                jokeArray.push({
                    title: child.data.title, 
                    text: child.data.selftext
                });
            });

            // Assinging the filled jokeArray to the session variable
            self.attributes['joke'] = jokeArray;
            self.emit(':saveState', true);

    }).on('error', function(e){
        self.emit(':tell', "Error");
        console.log("Got an error: ", e);
    });     
    this.emit('TellAJoke');
    });
},

'TellAJoke': function() {
    this.attributes['randomNumber'] = Math.floor(Math.random() * 8) +0;
   //This prints undefined
   console.log(this.attributes['joke']);
},

Now, I have read the similar question here, but I does not have sufficient reponses to explain whats going on there. Basically, I was hoping that due to this.emit(':saveState', true) the variable will persist, but it is undefined. Any ideas?

ffritz
  • 2,180
  • 1
  • 28
  • 64
  • Do you have to call TellAJoke using "this.emit" ? Do you have an option to call this function as TellAJoke(self) and then use self.emit to tell the joke to the user. – Amit Sep 22 '17 at 14:03
  • @Amit I changed the whole flow of this. I believe this is an async problem. – ffritz Sep 22 '17 at 14:04
  • In that case I believe you need to provide `.on('success', function(e){ //call tellajoke here })` – Amit Sep 22 '17 at 14:11

1 Answers1

1

Use emit inside the end block.

res.on('end', () => {
    this.emit('TellAJoke');
})

For error handling pass it on to the Unhandled or SessionEndedRequest Intents.

use emitWithState('') instead of emit('') to move on to another Intent.

Priyam Gupta
  • 250
  • 1
  • 14