Search code examples
javascriptnode.jsasynchronousnode-requestnode-async

async.each doesn't run callback function


I'm trying to do something after push data from reddit api to array, but callback function doesn't work at all. As you see the code, It's supposed to print Callback function works! but It doesn't. Is there any ideas about this?

let optForReddit = {
  method: 'GET',
  uri: 'https://www.reddit.com/domain/eroshare.com/new.json',
  json: true
}

  rp(optForReddit)
    .then(function(redditJSON) {
      let posts = redditJSON.data.children;
      let len = posts.length;
      let eroJson = [];
      async.each(posts, function(item, callback) {
          if (isVideo(item.data.url)) {
            eroJson.push(getAlbumId(item.data.url));
          }
      },    
      function(err) {
          console.log("Callback function works");
          if(err) console.log(err);
      });
    })
    .catch(function(err) {
      console.log(err);
    })

Solution

  • async.each(posts, function(item, callback) {
          if (isVideo(item.data.url)) {
            eroJson.push(getAlbumId(item.data.url));
          }
          callback();  // this callback is for informing that i am done processing one item in array.
      },    
      function(err) {
          //this function will be invoked when the callback() in the above body was called maximum time(e.g posts.length times)
          console.log("Callback function works");
          if(err) console.log(err);
      });
    

    this is because you are not calling callback function each time. callback when called tells the async function that i am done with the current execution and call next iteraion. You never called the callback().