Search code examples
javascriptnode.jsasynchronousnode-requestnode-async

How can I call callback function in async.eachSeries callback function


I'm trying to call callback function after eachSeries is done, but IT doesn't work at all. It doesn't print 2 that's supposed to print when It's called but It prints 4 after first function is called. Is there any idea about it? Thank you!

async.waterfall([
      function(callback) {
        console.log("1");
        let eroJson = [];
        rp(optForReddit).then(function(redditJSON) {
          let posts = redditJSON.data.children;
          async.eachSeries(posts, function(item, callback) {
            if (isVideo(item.data.url)) {
              eroJson.push(getAlbumId(item.data.url));
            }
            callback(); // callback function after eachSeries
          }, function() {
            callback(eroJson); // call next callback
          });
        })
      },
      function(redditJSON, callback) {
        console.log("2");
        callback() // call another function
      }
)],
     function(){
         console.log("Last one");
     }

);


Solution

  • Change the callback names. it seems like you are overriding callback Names

        async.waterfall([
              function(waterfallCallback) {
                console.log("1");
                let eroJson = [];
                rp(optForReddit).then(function(redditJSON) {
                  let posts = redditJSON.data.children;
                  async.eachSeries(posts, function(item, callback) {
                    if (isVideo(item.data.url)) {
                      eroJson.push(getAlbumId(item.data.url));
                    }
                    callback(); // callback function after eachSeries
                  }, function() {
                    waterfallCallback(eroJson); // call next callback
                  });
                })
              },
              function(redditJSON, waterfallCallback) {
                console.log("2");
                waterfallCallback();
              }
        )], function(){
                console.log("Done executing all waterfall functions");
        });