How to receive the result of an asynchronous function and move to Return?

Asked

Viewed 158 times

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

  • xml coming from the URL

  • This API request() has Promises? ie instead of callback you can use await request('https://URL_q_retorn_XML');?

  • This API request() has Promises? ie instead of callback you can use await request('https://URL_q_retorn_XML');?

  • 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.

  • tried using Wait but don’t know how. I am backend programmer. :)

  • 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 documentation request?

  • https://www.npmjs.com/package/request uses Promise

  • If you are using async you can use await before sitting down the variable that will be passed in Return

Show 4 more comments

1 answer

3


You need to return a trial, but in the case of request the API does not support Promises. An alternative would be to use the https://github.com/request/request-promise-native which has not been maintained for more than a year :(

So all I see is a solution, create a Promise that’s waiting for the result, and be this Promise return of function:

'use strict';

const request = require('request');
const xmlParser = require('xml2json');

module.exports.hello = async(event, context) => {
  // Retrieve XML form the URL
  return new Promise((resolve, reject) => {
    request('https://URL_q_retorn_XML', function(error, response, body) {
      // Convert XML into JSON
      if (!error && response.statusCode == 200) {
        const jsonResp = xmlParser.toJson(body);
        console.log('JSON output', jsonResp);
        resolve({
          statusCode: response.statusCode,
          body: jsonResp,
        });
      } else {
        console.log("Error " + response.statusCode);
        reject(response.statusCode);
      }
    })
  });
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.