Skip to content Skip to sidebar Skip to footer

How To Use Request Within Async.each In Node.js Express

In my node.js project, I need to make iterative API request so I'm using async.each method. The console complains that url is not defined and I understand this because I've only de

Solution 1:

It seems you're calling request with callbacks and all, and not just referencing it, which means you probably need an anonymous function call.

Also, if you want an array at the end, or whatever you're extending, you could just use async.map instead, and do something like

var urls = Object.keys(result.items).map(function(item) {
    return"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=" + result.items[item].contentDetails.videoId + "&key=xxx";
});

async.map(urls, function(url, callback) {
    request(url, function(err, response, body) {
        if (err) {
            returncallback(err);
        }
        callback(null, JSON.parse(body));
    });
}, function(err, extended) {
    if (err) {
        // handle error
    }
    // extended is an array containing the parsed JSONgetVideoDetailsCallback(null, extended); 
});

Solution 2:

If you want to get the results from each iteration. I suggest using async.map. Map returns an array of results to the final callback.

Here's an example,

varasync = require('async');

async.map([ 1, 2, 3, 4 ], function ( num, cb ) {
  cb(null, num);
}, function (error, results) {
  console.log(results);
});
// output: [ 1, 2, 3, 4 ] 

As for your code snippet, your second argument is the wrong type. You're invoking request which doesn't return a function. The second argument is expected to be a function so what you need to do is wrap the request around function definition.

async.map(urls, function(url, callback) {
  request(options, callback);
}, function (error, results) {
  // do something with results
});

Post a Comment for "How To Use Request Within Async.each In Node.js Express"