2017-02-12 92 views
1

我试图在将数据从reddit api推送到数组之后执行某些操作,但回调函数根本不起作用。当你看到代码时,它应该打印Callback function works!但它没有。对此有任何想法吗?async.each不运行回调函数

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

回答

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

,这是因为你没有调用回调函数每次。被调用时的回调函数告诉异步函数我完成了当前的执行并调用下一次迭代。你永远不会调用回调函数()。

+0

但我想在每个循环完成后调用回调函数。我能怎么做? – boombamboo

+0

就像你想连续执行循环?所以它按顺序执行? –

+0

是的!因此回调函数可以在所有事情完成后运行。 – boombamboo