[英]AWS Lambda - Nodejs function will not return data
我是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);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.