2015-08-16 74 views
1

有一個函數,它需要遍歷數組,對每個項目執行異步操作,然後最終回調給調用者。Node.js使用async.forEach與異步操作

我可以得到async.forEach工作的基本情況。 當我做到這一點,它的工作原理

async.forEach(documentDefinitions(), function (documentDefinition, callback) {    
    createdList.push(documentDefinition); 
    callback(); //tell the async iterator we're done 

}, function (err) { 
    console.log('iterating done ' + createdList.length); 
    callback(createdList); //tell the calling method we're done, and return the created docs. 
}); 

createdList的長度是正確的長度。

現在,我想通過循環每次執行另一個異步操作。所以我嘗試將代碼更改爲以下內容;

function insert(link, callback){ 
    var createList = []; 

    async.each(
     documentDefinitions(), 

     function iterator(item, callback) { 
      create(collectionLink, item, function (err, created) { 
       console.log('created'); 
       createdList.push(created); 
       callback(); 
      }); 
     }, 

     function (err) { 
      console.log('iterating done ' + createdList.length); 
      callback(createdList); 
     } 
    ); 
} 

其中創建()是我的新異步操作。 現在我得到一個無限循環,我們似乎從來沒有打回調(createdList);

我的事件試圖在異步create()方法的回調中移動callback(),但這兩者都不起作用。

請幫助我,我卡在回撥地獄!

+0

在'create'回調中調用'callback()'是實現這一點的方法。不知道爲什麼這不適合你。 – JohnnyHK

+0

也不確定。想知道是否因爲回調被定義了兩次。一次在循環中,再次在包含函數中。想知道它是否變得困惑。 –

+0

btw。 async.forEach和async.each有什麼區別? –

回答

0

將func更改爲以下修正它。

function insert(link, callback){ 
    var createdList = []; 
    async.each(
     documentDefinitions(), 

     function iterator(item, cb) { 
      create(collectionLink, item, function (err, created) { 
       console.log('created'); 
       createdList.push(created); 
       cb(); 
      }); 
     }, 

     function (err) { 
      console.log('iterating done ' + createdList.length); 
      callback(createdList); 
     } 
    ); 
} 

不確定,但我認爲它正在改變一個回調到cb的事件,做了伎倆。

這是一個範圍界定問題,他們正在混淆?