gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:37 25 4
gpt4 key购买 nike

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

最佳答案

一旦您在 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);
};

关于javascript - AWS Lambda - Nodejs 函数不会返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com