2016-08-20 224 views
0

我有一個與async.eachSeries問題 - 我用它來迭代數組和使用函數下載文件(請參閱源代碼) - 但回調從未被稱爲...我在做什麼有問題?我不知道的回調...異步eachSeries - 回調從未調用

function checkAndDownloadPlaylist(data,cb) { 
 

 
    async.eachSeries(data,function(val,callback) { 
 
     url=val.media[0]; 
 
     fileSize=val.fileSize; 
 
     checkAndDownloadItem(url,fileSize, callback); 
 
    }, function(error) { 
 
     // never called... 
 
     if(error) { 
 
      return cb(error); 
 
     } 
 
     cb(); 
 
    }); 
 

 
} 
 

 
function checkAndDownloadItem(url,fileSize,cb) { 
 

 
    if(checkedUrls.indexOf(url)==-1) { 
 
     fileName=getFileNameFromUrl(url); 
 
     filePath=path.join(config.movieDir,fileName); 
 

 
     // save file in usedFiles[] 
 
     d=new Date(); 
 
     usedFiles[fileName]=d.toISOString(); 
 

 
     fs.access(filePath, fs.constants.F_OK, function(error) { 
 
      checkedUrls.push(url); 
 

 
      if(error) { 
 
       // file is not there 
 
       winston.debug('file Missing, start DL: '+fileName); 
 
       download(url,filePath,cb); 
 
      }else{ 
 
       // file is there 
 
       winston.debug('file already there: '+fileName); 
 
       cb(null); 
 
      } 
 

 
     }); 
 
    } 
 
} 
 

 
function download(url,destination,cb) { 
 

 
    winston.debug('start DL: '+url); 
 

 
    var tmpDestination=destination+'.tmp'; 
 

 
    file=fs.createWriteStream(tmpDestination); 
 
    request = http.get(url, function(response) { 
 
     response.pipe(file); 
 
     file.on('finish', function() { 
 
      winston.debug('finished DL: '+url); 
 
      file.close(); 
 

 
      fs.renameSync(tmpDestination,destination); 
 
      cb(null); 
 
     }); 
 
    }).on('error', function(error) { 
 
     fs.unlinkSync(tmpDestination); 
 
     if(error) { 
 
      cb(error.message); 
 
      winston.log('notice','error DL: '+url); 
 
     } 
 
     cb(null); 
 
    }); 
 
}

+1

是的,有相當多的情況下, 'cb'永遠不會被調用;修復它們。 – Bergi

+0

該死的,現在我明白了 - 謝謝:) – cklm

回答

-1

嘗試更改回調函數`checkAndDownloadItem到CB

function checkAndDownloadPlaylist(data,cb) { 

    async.eachSeries(data,function(val,cb) { 
     url=val.media[0]; 
     fileSize=val.fileSize; 
     checkAndDownloadItem(url,fileSize, cb); 
    }, function(error) { 
     if(error) { 
      throw error; 
     } 
     console.log('Done!'); 
    }); 
} 
+0

變量名稱使零差異。最後省略「cb」的調用肯定是錯誤的。 – Bergi