承诺性能问题。 读文件太慢了

我使用承诺读取硬盘驱动器中的10000多个文件,并在确切的位置find一个数字。 我使用glob来返回文件名,并find每个文件我运行方法readFile(readFile返回作为promisse)。 当所有的文件被处理时,我可以继续我的工作。

function readFilesGlob(globPath,options,progressCallback){ return new Promise(function (fulfill, reject){ glob(globPath, options, function (err, files) { var readPromisses=[]; for(var id in files){ readPromisses.push(readFile(files[id])); } Promise.all(readPromisses).then( function(filesContents){ fulfill(filesContents) } ); }); }); } 

所有的承诺都只在完成时才完成,无法显示处理进度

 function readFilesGlob(globPath,options,progressCallback){ return new Promise(function (fulfill, reject){ glob(globPath, options, function (err, files) { var readPromisses=[]; for(var id in files){ readFile(files[id]).then(function(data){ //everything shows at the same time, like i was using the Promise.all console.log(data) }) } //just testing the speed of the return in the console.log above fulfill(); }); }); 

问题是。 它太慢了,我只有几分钟后才能有回报(或者当我内存不足时)

即时通讯使用承诺错误的即时通讯。 有人能给我一个更具性质的例子来阅读有承诺的文件列表吗?

这似乎是一个非常好的解决scheme的asynchronous包!

签出eachfunction: https : //caolan.github.io/async/docs.html#each

例:

 // assuming openFiles is an array of file names async.each(openFiles, function(file, callback) { // Perform operation on file here. console.log('Processing file ' + file); if( file.length > 32 ) { console.log('This file name is too long'); callback('File name too long'); } else { // Do work to process file here console.log('File processed'); callback(); } }, function(err) { // if any of the file processing produced an error, err would equal that error if( err ) { // One of the iterations produced an error. // All processing will now stop. console.log('A file failed to process'); } else { console.log('All files have been processed successfully'); } }); 

我在几乎所有的项目中都使用asynchronous包,速度很快,并且具有<3的特性

替代方法:使用队列系统

build立一个队列系统,我和Kue一起工作,这样你也可以检查你的'任务'

我认为在你的循环中你需要这样的东西

 readPromisses.push( new Promise( function(y,n) { readFile(files[id]); y();} ) ) 

然后readFile将在Promise开始执行asynchronous时被调用。 这只是一个build议,我没有testing过,所以你可能需要调整一下。

这是一个骨架,也许这将有助于

 var firstCall = new Promise((y, n) => setTimeout( () => y(Math.random()), 500 )); var secondCall = (arg) => { return new Promise((y, n) => setTimeout( () => y(Math.random() + ' ' + arg), 200 )); } var rejectCall = () => new Promise((y, n) => setTimeout( () => n(true), 400 )); Promise.all([ firstCall, secondCall('withArg'), ]).then( (data) => { console.log( 'ALL: First Call result:', data[0]); console.log( 'ALL: Second Call result:', data[1]); }).catch( (err) => { console.log( 'Promise.all caught reject or error:', err); }); 

如果I / O出现问题,可以将“文件”数组拆分成块,然后链接这些块。

 chunks.reduce((result, chunk) => { return Promise.all(chunk.map(file=> promiseRead(file)) .then(results => dealWithChunkResults(results) }, Promise.resolve())