Friday, 28 April 2017

Reference variables in alexa-app promise and elasticsearch js promise

This is a question about callbacks, promises and variable scope in JS. Seems the all thing is a little new to me.

I have a running alexa-app instance in nodejs where intents are defined as:

app.intent('Search', {
        "slots": {"queryslot": "LITERAL"},
        "utterances": ["{Search for} {(.*)|queryslot}",]
    }, **function (req, res) {
    ...
        res.say("This is fine");
    });**

(res.say is a call on the response function say, which formats an Output Speeach for Alexa).

Inside the function callback I need to run an elastic search request, something like:

app.intent('Search', {
    "slots": {"queryslot": "LITERAL"},
    "utterances": ["{Search for} {(.*)|queryslot}",]
}, function (req, res) {
    res.say("This is fine");
//Setup client here
client.search({
        q: query
    }).then(function (resp) {
        var hits = resp.hits.hits;
        //Call res.say("inform on hits here")
    });
});

The variable, res is out of scope in this promise and I cannot directly involve it.

Therefore I define a function in the first callback:

app.intent('Search', {
        "slots": {"queryslot": "LITERAL"},
        "utterances": ["{Search for} {(.*)|queryslot}",]
    }, function (req, res) {
    ...
        res.say("This is fine");
        **function invokeThroughRes(text) {
           console.log(text);
           res.say(text);
         }**
    });

that should have access on the local variable, and I call it in the elastic search promise:

client.search({
        q: query
    }).then(function (resp) {
        var hits = resp.hits.hits;
        **invokeThroughRes("test");**
    });

Although I test that the res is available (or can be returned), I cannot invoke the function say from there.

Is there any better (or working) practice to move variables around? Someway to return some variable (hits) from the Elastic Search Promise for example to the app.intent callback? As I do not have much js experience, any help will be appreciated.



via Al-Punk

No comments:

Post a Comment