2
I have the following code in nodejs in a lambda function in AWS that has been defined using serverless.
The goal of this function is to read a URL that will return an XML, transform into JSON and display this JSON.
When I run the function I can see JSON but Return is empty. I can see the JSON pq made a console.log within the request function.
How do I retrieve the answer within Return?
'use strict';
module.exports.hello = async (event, context) => {
let jsonResp='';
//Retrieve XML form the URL
var request = require('request');
request('https://URL_q_retorn_XML', function (error, response, body) {
//COnvert XML into JSON
if (!error && response.statusCode == 200) {
let xmlParser = '';
xmlParser = require('xml2json');
jsonResp = xmlParser.toJson(body);
console.log('JSON output',jsonResp);
//TODO retrieve s3 object and insert JSON inside it.
require('aws-sdk/clients/s3');
}
else {
console.log("Error "+response.statusCode)
}
})
return {
statusCode: 200,
body: jsonResp,
};
// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};
What gives
console.log(body);
?– Sergio
xml coming from the URL
– zwitterion
This API
request()
has Promises? ie instead of callback you can useawait request('https://URL_q_retorn_XML');
?– Sergio
This API
request()
has Promises? ie instead of callback you can useawait request('https://URL_q_retorn_XML');
?– Sergio
I know it is something like asynchronism. because Return comes first and the jsonResp variable is empty. You would have to make Return come after the request.
– zwitterion
tried using Wait but don’t know how. I am backend programmer. :)
– zwitterion
I understand the problem well, my question is if the request API has Promises, as it solves the problem using
await
. What is the link to this documentationrequest
?– Sergio
https://www.npmjs.com/package/request uses Promise
– zwitterion
If you are using async you can use await before sitting down the variable that will be passed in Return
– davibusanello