2017-01-10 27 views
0

我正試圖在一個對象數組上運行異步循環async.each。 在數組中的每個對象上,我試圖按順序運行兩個函數(使用promises)。問題是async.each僅運行第一個關鍵字。async.each在使用promise時不會迭代

在以下代碼中,getKeywords從文件加載一些關鍵字,然後返回一個關鍵字對象數組。每個關鍵字對象都被放到searchKeyword中進行搜索。然後使用InsertSearchResults將搜索結果放入數據庫。

在我看來,每個關鍵字應該被並行處理,並且搜索和插入功能被鏈接。

getKeywords(keys).then(function(keywords) { 
    async.each(keywords, function(keywordObject, callback) { 
     searchKeyword(keywordObject).then(function(searchResults) { 
      return insertSearchResults(searchResults, db, collections); 
     }).then(function(result) { 
      console.log("here"); 
      callback(); 
     }) 
    }) 
}) 
+0

你可以嘗試調用捕獲'err'的可選回調嗎? –

回答

0

您只使用.then()回調,以便處理成功。

但是,您還應該添加一些.catch()回調來處理錯誤。

很有可能你會得到沒有處理的錯誤,也沒有任何反應。

例如:

  // ... 
     }).then(function(result) { 
      console.log("here"); 
      callback(); 
     }).catch(function (error) { 
      console.log('Error:', error); 
      callback(error); 
     }); 
0

原來,是我在getKeywords功能作出了錯誤。 我正在讀取一個文件,然後通過使用for循環遍歷每行並將結果推送到一個數組。這個數組然後被函數返回。

async.each工作正常,但只能接收長度爲1的數組進行迭代。

我通過改變for循環的循環async.each

function getKeywords(keywordsFilename){ 
    //get keywords from the file 
    return new Promise(function (resolve, reject) { 
     var keywords = []; 
     fs.readFile(keywordsFilename, function read(err, data) { 
      if (err) { 
       reject(err); 
      } 
      content = data.toString(); 
      var lines = content.split("\n"); 
      async.each(lines, function(line, callback) { 
       if (line[0] === "#" || line == "") { 
        callback(); 
       } 
       else { 
        keywords.push(extractKeyword(line)); 
        callback(); 
       } 
      }, function (err) { 
       resolve(keywords); 
      }); 
     }); 
    }); 
} 

寫出幫助問題解決了這個問題,讓我知道我是否應該刪除的問題。

感謝您的幫助Mukesh Sharma和rsp。

相關問題