我使用回调时为什么无法启动实例?

时间:2017-06-28 12:39:33

标签: node.js amazon-ec2 aws-lambda alexa alexa-skills-kit

我对lambda函数很新,如果这个问题非常愚蠢,请道歉。 下面代码的第一部分工作,它启动ec2实例但是如果我将它链接到Alexa则不起作用

var aws = require("aws-sdk");
var https=require('https')

exports.handler = (event, context, callback) => {


    try{

        if (event.session.new) {
    //New Session
    console.log("NEW SESSION")
    }

    switch (event.request.type){  
    case "IntentRequest":
    // > Intent Request
    console.log(`INTENT REQUEST`)
    switch(event.request.intent.name){

    case "StartecInsatnce":
        console.log(`Test msg`)
                             var ec2=new aws.EC2({region: 'us-east-1'});
       var endpoint= ec2.startInstances({InstanceIds: ['i-0a20b89becb6fcb7e']}, function(err,data) {
                                           if (err) console.log(err,err.stack);
                                           else console.log(data);
                                           context.done(err,data);
                                           }); 
                              callback(null, "some success message");                                          


                                           }
                                           break;
       default: 
          context.fail(`INVALID REQUEST TYPE: ${event.request.type}`)
    }
}
catch(error) { context.fail(`EXCEPTION: ${error}`) }

}

所以我使用下面的代码,虽然发送响应但无法启动ec2实例。请帮忙

var aws = require("aws-sdk");
var https=require('https')

exports.handler = (event, context, callback) => {


    try{

        if (event.session.new) {
    //New Session
    console.log("NEW SESSION")
    }

    switch (event.request.type){

    case "IntentRequest":
    // > Intent Request
    console.log(`INTENT REQUEST`)
    switch(event.request.intent.name){

    case "StartecInsatnce":
    onIntent(event.request,
        event.session,
        function callback(sessionAttributes, speechletResponse) {
          context.succeed(buildResponse(sessionAttributes, speechletResponse));
        });


      //      callback(null, "some success message");                                                                             

               }//end of inner switch
                                           break;

    default: 
          context.fail(`INVALID REQUEST TYPE: ${event.request.type}`)        
    }
}
catch(error) { context.fail(`EXCEPTION: ${error}`) }
//Helpers
generateResponse = (sessionAttributes, speechletResponse) => {
return{   
    version: "1.0",
    sessionAttributes: "sessionAttributes",
    response: "speechletResponse"
    }
   }  
}
function onIntent(intentRequest, session, callback) {
    var intent = intentRequest.intent,
    intentName = intentRequest.intent.name;
    var cardTitle = intent.name;
    console.log(`Test msg`)
    var sessionAttributes={}
         var shouldEndSession = false;
    speechOutput = "instance started.";
       var ec2=new aws.EC2({region: 'us-east-1'});  
       var endpoint= ec2.startInstances({InstanceIds: ['i-0a20b89becb6fcb7e']}, function(err,data) {
                                           if (err) console.log(err,err.stack);
                                           else console.log(data);
                                           context.done(err,data);

                                          }); 
                                          console.log("end="+endpoint) 
    callback(sessionAttributes,
    buildSpeechletResponse(cardTitle, speechOutput,  shouldEndSession));

    }

    function buildSpeechletResponse(title, output, shouldEndSession) {
    return {
      outputSpeech: {
        type: "PlainText",
        text: output
      },
      card: {
        type: "Simple",
        title: "SessionSpeechlet - " + title,
        content: "SessionSpeechlet - " + output
      },

      shouldEndSession: shouldEndSession
    };
  }
function buildResponse(sessionAttributes, speechletResponse) {
    return {
      version: "1.0",
      sessionAttributes: sessionAttributes,
      response: speechletResponse
    };
  }

1 个答案:

答案 0 :(得分:0)

您将异步代码视为同步代码。

var endpoint= ec2.startInstances({InstanceIds: ['i-0a20b89becb6fcb7e']}, function(err,data) {
                                       if (err) console.log(err,err.stack);
                                       else console.log(data);
                                       context.done(err,data);
                                       }); 
                          callback(null, "some success message");                                          

这段代码有什么作用?

按顺序:

  • 构建并启动对ec2.startInstances的异步请求
  • 立即调用callback()
  • 可能允许API请求完成
  • 可能到达context.done()。目前尚不清楚为什么你同时使用callback(),但也许我忽略了一些东西。

但似乎你需要从ec2.startInstances调用延续函数内部的回调,以便它被延迟,而不是在外面,它将在之前执行 {{1} }完成,因为你没有将控制权返回给事件循环。