1

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

1 Answer 1

1
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().

Sign up to request clarification or add additional context in comments.

10 Comments

but I want to call the callback function after the each loop is done. how can I do?
like you want to execute loop serially? so it executes in order?
yes! so the callback function can run after everything is done.
I solved the problem! I just had to use eachSeries not each. Thank you for help anyways!
I have a question, eachSeries in waterfall would work or not?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.