Monday, 12 June 2017

Multiple API calls with Async & Request Package (NodeJS / Express)

I am trying to implement async and request into an asynchronous API request action within one of my routers. The end point is just a query string and I'm trying to return an an array or object with the result of all of the calls. So far there are just two:

router.get('/', function(req, res) {
    async.parallel([
        function(next) {
            request(queryString + 'end point string', function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    var unsPAM = JSON.parse(body);
                };
                console.log(error);
            });
        },
        function(next) {
            request(queryString + 'end point string', function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    var unsAll = JSON.parse(body);
                };
                console.log(error);
            });
        }], 
        function(err, results) {
            res.render("api-results", [results]);
        });
    });

This is the just of what I'm trying to do. If I console.log the result of each variable after the request it works properly, but nothing is being returned and my ejs template is not being served.

I have also tried using something like the below in various formats (array/object form) but I cannot seem to get it working:

res.render("api-results", { unsPAM: unsPAM, unsAll: unsAll });

I think its because the result of the request's aren't making it to the async array somehow. Any advice/best practice solutions/change of ideas would be greatly appreciated.

Thank you.



via Lukon

No comments:

Post a Comment