Saturday, 15 April 2017

How to use "this" inside a callback?

I have a rest service on the other end of the url in my code below that returns the names of all of the objects in an s3 bucket. I'm trying to create a simple Alexa skill that tells me how many objects are in that bucket. My problem is that within the http get request the term "this" is not referencing the same thing as it is outside of the http get request. How can I use "this" inside the get request or return the "count" variable from my http get request?

"use strict";
var Alexa = require("alexa-sdk");
var Client = require('node-rest-client').Client;

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'Launch Request': function() {
        this.emit('CountItems');
    },
    'ContentsIntent': function() {
        this.emit('CountItems');
    },
    'CountItems': function() {
        var client = new Client();
        var count = undefined;
        client.get("URL", function (data, response) {
            console.log(data['Keys'].length);
            count = data['Keys'].length;
        });
        this.emit(':tell', 'There are ' + count + ' items in your s3 bucket.');
    }
};



via Chris Bell

No comments:

Post a Comment