简体   繁体   English

async.each 不运行回调函数

[英]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.我试图在将数据从 reddit api 推送到数组后做一些事情,但回调函数根本不起作用。 As you see the code, It's supposed to print Callback function works!正如你看到的代码,它应该打印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);
    })
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().您从未调用过 callback()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM