0

I have a simple node Express app that has a service that makesa call to a node server. The node server makes a call to an AWS web service. The AWS simply lists any S3 buckets it's found and is an asynchronous call. The problem is I don't seem to be able to get the server code to "wait" for the AWS call to return with the JSON data and the function returns undefined.

I've read many, many articles on the web about this including promises, wait-for's etc. but I think I'm not understanding the way these work fully!

This is my first exposer to node and I would be grateful if somebody could point me in the right direction?

Here's some snippets of my code...apologies if it's a bit rough but I've chopped and changed things many times over!

Node Express;

var Httpreq = new XMLHttpRequest(); // a new request

Httpreq.open("GET","http://localhost:3000/listbuckets",false);
Httpreq.send(null);

console.log(Httpreq.responseText);

return Httpreq.responseText;  

Node Server

app.get('/listbuckets', function (req, res) {

var bucketData = MyFunction(res,req);

console.log("bucketData: " + bucketData);

});

function MyFunction(res, req) {

var mydata;
var params = {};

res.send('Here are some more buckets!');

var request = s3.listBuckets();

// register a callback event handler
request.on('success', function(response) {
    // log the successful data response
    console.log(response.data);
    mydata = response.data; 
});

// send the request
request.
on('success', function(response) {
  console.log("Success!");
}).
on('error', function(response) {
  console.log("Error!");
}).
on('complete', function() {
  console.log("Always!");
}).
send();

return mydata;
}
Mark Beynon
  • 265
  • 1
  • 3
  • 19
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Brahma Dev Sep 21 '17 at 09:58

2 Answers2

0

Use the latest Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make HTTP calls. It has built-in support with Promise.

fetch('http://localhost:3000/listbuckets').then(response => {
    // do something with the response here
}).catch(error => {
    // Error :(
})
Birkhoff Lee
  • 788
  • 10
  • 21
0

I eventually got this working with;

const request = require('request');

request(url, function (error, response, body) {

    if (!error && response.statusCode == 200) {

        parseString(body, function (err, result) {
            console.log(JSON.stringify(result));
        });

        // from within the callback, write data to response, essentially returning it.
        res.send(body);
    }
    else {
        // console.log(JSON.stringify(response));
    }
})
Mark Beynon
  • 265
  • 1
  • 3
  • 19