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

我是NodeJS函数调用的新手,我一直在屏幕上敲打我的头几个小时,所有的search引擎都没有帮助。

因此,我拥有的是一个AWS Lambda函数,它接收一个具有单个ID号的JSON对象。 这个ID号码被传递,并最终作为myid发送到getJson函数。 这部分工作正在使用NPM的REQUEST模块,它接触到Web服务并回收数据。 当我console.log(正文)我看到我需要的JSON对象。

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

我试着在函数中使用callback函数,它确实调用了函数,但是即使这个函数也不会返回数据给我使用。 我已经硬编码的JSON到一个variables,并返回它,它的工作原理…但是,如果我使用的请求它只是不会给它回给我。

我希望这是简单的事情…非常感谢!

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); } 

一旦在JavaScript中调用了一个以callback为参数的函数,就不能通过返回来获取callback的值,因为这个函数是asynchronous执行的。 为了从callback中获得值,这个callback最终必须调用lambda函数callback函数。

在你的情况下,“returnsData”函数需要调用lambdacallback函数。

这将是结构:

 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); };