AWS Lambda - Nodejs函数不会返回数据

Jos*_*osh 5 javascript json node.js aws-lambda

我是NodeJS函数调用的新手,现在我已经在屏幕上敲了几个小时,而我所有的谷歌搜索都没有帮助.

所以我所拥有的是一个AWS Lambda函数,它接收一个具有单个ID号的JSON对象.此ID号传递并最终作为myid发送到getJson函数.这部分正在运行,它正在使用NPM的REQUEST模块,它可以访问Web服务并撤回数据.当我在console.log(body)中看到我需要的JSON对象时.

问题是我无法让它返回数据,所以我可以在其他地方使用JSON.我尝试了CALLBACK(BODY),RETURN(BODY),但没有任何东西都能让我回复使用的数据.

我尝试在函数中使用回调函数,它确实调用了该函数,但即使该函数也不会返回数据供我使用.我已经将JSON硬编码为变量并返回它并且它可以工作......但是如果我使用REQUEST它就不会将它还给我.

我希望这很简单......非常感谢!

Calling the function:
            query_result.success = 1;
            query_result.message = "Applicant Data Found";
            query_result.data = getJson(201609260000003, returningData);


function getJson(myid, callback){
    request('http://server.com/service1.asmx/Get_Status_By_External_Id?externalId=' + myid + '',
        function (error, response, body) {
        console.log(body); // I see the JSON results in the console!!!
        callback (body); // Nothing is returned.
        }

    );

}

function returningData(data){
    console.log("ReturningData Function Being Called!");
    var body = '{"Error":null,"Message":null,"Success":true,"ExternalId":"201609260000003","SentTimeStamp":"11/22/2016 1:07:36 PM","RespTimeStamp":"11/22/2016 1:08:32 PM","RespTot":"SRE"}';
    return JSON.parse(body);
}
Run Code Online (Sandbox Code Playgroud)

Dig*_*aen 8

一旦在JavaScript中调用了具有回调作为参数的函数,就无法通过返回从回调中获取值,因为此函数是异步执行的.为了从回调中获取值,此回调必须最终调用lambda函数回调函数.

在您的情况下,函数"returningData"需要调用lambda回调函数.

这将是结构:

exports.lambda = (event, lambdaContext, callback) => { // this is the lambda function

  function returningData(data){
    console.log("ReturningData Function Being Called!");
    var body = '{"Error":null,"Message":null,"Success":true,"ExternalId":"201609260000003","SentTimeStamp":"11/22/2016 1:07:36 PM","RespTimeStamp":"11/22/2016 1:08:32 PM","RespTot":"SRE"}';
    callback(null, JSON.parse(body)); // this "returns" a result from the lambda function
  }

  function getJson(myid, callback2){
    request('http://server.com/service1.asmx/Get_Status_By_External_Id?externalId=' + myid + '', function (error, response, body) {
      console.log(body); // I see the JSON results in the console!!!
      callback2(body); 
    });
  }

  query_result.success = 1;
  query_result.message = "Applicant Data Found";
  query_result.data = getJson(201609260000003, returningData);
};
Run Code Online (Sandbox Code Playgroud)