Javascript Js不';不执行匿名函数-aws lambda-alexa skill

Javascript Js不';不执行匿名函数-aws lambda-alexa skill,javascript,node.js,aws-lambda,httprequest,alexa,Javascript,Node.js,Aws Lambda,Httprequest,Alexa,我目前正在为我的智能家居学习Alexa技能。 我创建了一个Lambda函数,并希望向服务器发出http请求。但它不会执行我的任何其他功能 lambda代码示例: /* This code has been generated from your interaction model by skillinator.io /* eslint-disable func-names */ /* eslint quote-props: ["error", "consistent"]*/ // Ther

我目前正在为我的智能家居学习Alexa技能。 我创建了一个Lambda函数,并希望向服务器发出http请求。但它不会执行我的任何其他功能

lambda代码示例:

/* This code has been generated from your interaction model by skillinator.io

/* eslint-disable  func-names */
/* eslint quote-props: ["error", "consistent"]*/

// There are three sections, Text Strings, Skill Code, and Helper Function(s).
// You can copy and paste the contents as the code for a new Lambda function, using the alexa-skill-kit-sdk-factskill template.
// This code includes helper functions for compatibility with versions of the SDK prior to 1.0.9, which includes the dialog directives.



 // 1. Text strings =====================================================================================================
 //    Modify these strings and messages to change the behavior of your Lambda function

const request = require("request");
let speechOutput;
let reprompt;
let welcomeOutput = "Hallo xyz!";
let welcomeReprompt = "xy";
// 2. Skill Code =======================================================================================================
"use strict";
const Alexa = require('alexa-sdk');
const APP_ID = "my id";  // TODO replace with your app ID (OPTIONAL).
speechOutput = '';
const handlers = {
    'LaunchRequest': function () {
        this.emit(':ask', welcomeOutput, welcomeReprompt);
    },
    'AMAZON.HelpIntent': function () {
        speechOutput = 'Placeholder response for AMAZON.HelpIntent.';
        reprompt = '';
        this.emit(':ask', speechOutput, reprompt);
    },
   'AMAZON.CancelIntent': function () {
        speechOutput = 'Placeholder response for AMAZON.CancelIntent';
        this.emit(':tell', speechOutput);
    },
   'AMAZON.StopIntent': function () {
        speechOutput = 'Placeholder response for AMAZON.StopIntent.';
        this.emit(':tell', speechOutput);
   },
   'SessionEndedRequest': function () {
        speechOutput = '';
        //this.emit(':saveState', true);//uncomment to save attributes to db on session end
        this.emit(':tell', speechOutput);
   },
    'LichtIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let zimmerSlotRaw = this.event.request.intent.slots.zimmer.value;
        console.log(zimmerSlotRaw);
        let zimmerSlot = resolveCanonical(this.event.request.intent.slots.zimmer);
        console.log(zimmerSlot);
        let was_lichtSlotRaw = this.event.request.intent.slots.was_licht.value;
        console.log(was_lichtSlotRaw);
        let was_lichtSlot = resolveCanonical(this.event.request.intent.slots.was_licht);
        console.log(was_lichtSlot);












        //THIS IS THE PART WHERE I NEED HELP!!



        MakeRequest(function(data){
            console.log("asddd");
            speechOutput = "This is a place holder response for the intent named LichtIntent, which includes dialogs. This intent has 2 slots, which are zimmer, and was_licht. Anything else?";


            var speechOutput = data;


            this.emit(':ask', speechOutput, speechOutput);

        });

        console.log("asdww");

        //DOWN TO HERE!!








    },
    'StromIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let geraet_stromSlotRaw = this.event.request.intent.slots.geraet_strom.value;
        console.log(geraet_stromSlotRaw);
        let geraet_stromSlot = resolveCanonical(this.event.request.intent.slots.geraet_strom);
        console.log(geraet_stromSlot);
        let wasSlotRaw = this.event.request.intent.slots.was.value;
        console.log(wasSlotRaw);
        let wasSlot = resolveCanonical(this.event.request.intent.slots.was);
        console.log(wasSlot);

        //Your custom intent handling goes here
        speechOutput = "This is a place holder response for the intent named StromIntent, which includes dialogs. This intent has 2 slots, which are geraet_strom, and was. Anything else?";
        this.emit(':ask', speechOutput, speechOutput);
    },
    'FrageIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let geraetSlotRaw = this.event.request.intent.slots.geraet.value;
        console.log(geraetSlotRaw);
        let geraetSlot = resolveCanonical(this.event.request.intent.slots.geraet);
        console.log(geraetSlot);
        let was_frageSlotRaw = this.event.request.intent.slots.was_frage.value;
        console.log(was_frageSlotRaw);
        let was_frageSlot = resolveCanonical(this.event.request.intent.slots.was_frage);
        console.log(was_frageSlot);

        //Your custom intent handling goes here
        speechOutput = "This is a place holder response for the intent named FrageIntent, which includes dialogs. This intent has 2 slots, which are geraet, and was_frage. Anything else?";
        this.emit(':ask', speechOutput, speechOutput);
    },
    'TuerIntent': function () {
        //delegate to Alexa to collect all the required slot values
       let filledSlots = delegateSlotCollection.call(this);
        speechOutput = '';
        //any intent slot variables are listed here for convenience

        let zeitSlotRaw = this.event.request.intent.slots.zeit.value;
        console.log(zeitSlotRaw);
        let zeitSlot = resolveCanonical(this.event.request.intent.slots.zeit);
        console.log(zeitSlot);

        //Your custom intent handling goes here
        speechOutput = "This is a place holder response for the intent named TuerIntent, which includes dialogs. This intent has one slot, which is zeit. Anything else?";
        this.emit(':ask', speechOutput, speechOutput);
    },  
    'Unhandled': function () {
        speechOutput = "The skill didn't quite understand what you wanted.  Do you want to try something else?";
        this.emit(':ask', speechOutput, speechOutput);
    }
};

exports.handler = (event, context) => {
    const alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    // To enable string internationalization (i18n) features, set a resources object.
    //alexa.resources = languageStrings;
    alexa.registerHandlers(handlers);
    //alexa.dynamoDBTableName = 'DYNAMODB_TABLE_NAME'; //uncomment this line to save attributes to DB
    alexa.execute();
};

//    END of Intent Handlers {} ========================================================================================
// 3. Helper Function  =================================================================================================










//THESE ARE MY HELPER FUNCTIONS
    function url(){
        console.log("asd");
        return " my server ip";
    }
    function MakeRequest(callback){
        console.log("hallo!");
        request.get(url(), function(error, response, body){

            console.log("****************************************");
            console.log(response);
            console.log("****************************************");

        console.log(error);     
        console.log("****************************************");

        console.log(body);
        console.log("****************************************");

        callback("erfolg!");
    });
    console.log("hffggh");
}

//DOWN TO HERE!!






















function resolveCanonical(slot){
    //this function looks at the entity resolution part of request and returns the slot value if a synonyms is provided
    let canonical;
    try{
        canonical = slot.resolutions.resolutionsPerAuthority[0].values[0].value.name;
    }catch(err){
        console.log(err.message);
        canonical = slot.value;
    };
    return canonical;
};

function delegateSlotCollection(){
  console.log("in delegateSlotCollection");
  console.log("current dialogState: "+this.event.request.dialogState);
    if (this.event.request.dialogState === "STARTED") {
      console.log("in Beginning");
      let updatedIntent= null;
      // updatedIntent=this.event.request.intent;
      //optionally pre-fill slots: update the intent object with slot values for which
      //you have defaults, then return Dialog.Delegate with this updated intent
      // in the updatedIntent property
      //this.emit(":delegate", updatedIntent); //uncomment this is using ASK SDK 1.0.9 or newer

      //this code is necessary if using ASK SDK versions prior to 1.0.9 
      if(this.isOverridden()) {
            return;
        }
        this.handler.response = buildSpeechletResponse({
            sessionAttributes: this.attributes,
            directives: getDialogDirectives('Dialog.Delegate', updatedIntent, null),
            shouldEndSession: false
        });
        this.emit(':responseReady', updatedIntent);

    } else if (this.event.request.dialogState !== "COMPLETED") {
      console.log("in not completed");
      // return a Dialog.Delegate directive with no updatedIntent property.
      //this.emit(":delegate"); //uncomment this is using ASK SDK 1.0.9 or newer

      //this code necessary is using ASK SDK versions prior to 1.0.9
        if(this.isOverridden()) {
            return;
        }
        this.handler.response = buildSpeechletResponse({
            sessionAttributes: this.attributes,
            directives: getDialogDirectives('Dialog.Delegate', null, null),
            shouldEndSession: false
        });
        this.emit(':responseReady');

    } else {
      console.log("in completed");
      console.log("returning: "+ JSON.stringify(this.event.request.intent));
      // Dialog is now complete and all required slots should be filled,
      // so call your normal intent handler.
      return this.event.request.intent;
    }
}


function randomPhrase(array) {
    // the argument is an array [] of words or phrases
    let i = 0;
    i = Math.floor(Math.random() * array.length);
    return(array[i]);
}
function isSlotValid(request, slotName){
        let slot = request.intent.slots[slotName];
        //console.log("request = "+JSON.stringify(request)); //uncomment if you want to see the request
        let slotValue;

        //if we have a slot, get the text and store it into speechOutput
        if (slot && slot.value) {
            //we have a value in the slot
            slotValue = slot.value.toLowerCase();
            return slotValue;
        } else {
            //we didn't get a value in the slot.
            return false;
        }
}

//These functions are here to allow dialog directives to work with SDK versions prior to 1.0.9
//will be removed once Lambda templates are updated with the latest SDK

function createSpeechObject(optionsParam) {
    if (optionsParam && optionsParam.type === 'SSML') {
        return {
            type: optionsParam.type,
            ssml: optionsParam['speech']
        };
    } else {
        return {
            type: optionsParam.type || 'PlainText',
            text: optionsParam['speech'] || optionsParam
        };
    }
}

function buildSpeechletResponse(options) {
    let alexaResponse = {
        shouldEndSession: options.shouldEndSession
    };

    if (options.output) {
        alexaResponse.outputSpeech = createSpeechObject(options.output);
    }

    if (options.reprompt) {
        alexaResponse.reprompt = {
            outputSpeech: createSpeechObject(options.reprompt)
        };
    }

    if (options.directives) {
        alexaResponse.directives = options.directives;
    }

    if (options.cardTitle && options.cardContent) {
        alexaResponse.card = {
            type: 'Simple',
            title: options.cardTitle,
            content: options.cardContent
        };

        if(options.cardImage && (options.cardImage.smallImageUrl || options.cardImage.largeImageUrl)) {
            alexaResponse.card.type = 'Standard';
            alexaResponse.card['image'] = {};

            delete alexaResponse.card.content;
            alexaResponse.card.text = options.cardContent;

            if(options.cardImage.smallImageUrl) {
                alexaResponse.card.image['smallImageUrl'] = options.cardImage.smallImageUrl;
            }

            if(options.cardImage.largeImageUrl) {
                alexaResponse.card.image['largeImageUrl'] = options.cardImage.largeImageUrl;
            }
        }
    } else if (options.cardType === 'LinkAccount') {
        alexaResponse.card = {
            type: 'LinkAccount'
        };
    } else if (options.cardType === 'AskForPermissionsConsent') {
        alexaResponse.card = {
            type: 'AskForPermissionsConsent',
            permissions: options.permissions
        };
    }

    let returnResult = {
        version: '1.0',
        response: alexaResponse
    };

    if (options.sessionAttributes) {
        returnResult.sessionAttributes = options.sessionAttributes;
    }
    return returnResult;
}

function getDialogDirectives(dialogType, updatedIntent, slotName) {
    let directive = {
        type: dialogType
    };

    if (dialogType === 'Dialog.ElicitSlot') {
        directive.slotToElicit = slotName;
    } else if (dialogType === 'Dialog.ConfirmSlot') {
        directive.slotToConfirm = slotName;
    }

    if (updatedIntent) {
        directive.updatedIntent = updatedIntent;
    }
    return [directive];
}
我使用“请求”模块来处理我的http请求,我想你们都知道这个模块

当我测试我的函数时,它不会给我任何运行时错误! 但是来自MakeRequest调用和request.get调用的匿名函数不会执行,我也不知道为什么。 例如,控制台输出:

你好

Asd(非常有趣..它获取请求的参数。get..错误必须在调用中的第二个参数(anon函数本身?)和anon函数的开始之间)

hffggh

asdww

-anon.函数中的console.logs不显示

我可能不明白为什么MakeRequest会起作用。不运行->因为它的回调从未出现。但是为什么这个请求不起作用??我将必要的部分(MakeRequest和helper函数)粘贴到了一个普通的节点项目中,它成功了-脸掌。。。。我几乎要哭了

我的目标:我希望收到服务器的响应….-就这些。但它不会进入我可以访问响应对象的函数中

(向下滚动至辅助功能)

请帮帮我,伙计们,我真的可以把头撞到墙上


Reguards

我无法从你的问题中看出你的评论,以及预期或报告的输入或输出。你能回答这个问题并澄清你得到的确切结果吗?
MakeRequest
是在哪里定义的?另外,不要
“严格使用”需要在所有其他语句之前吗?我猜是
MakeRequest(函数(数据){…})
代码。通过使用
函数(数据)
而不是箭头函数
(数据)=>{…}
可以将
this
关键字重新绑定到新的函数范围,而不是Alexa发射器,事件会漂移到空区(另请参见:)