2017-04-12 33 views
1

我陷入了nodejs异步的问题。 我想调整文件夹中的图像大小,resize是一个可执行的二进制文件。 问题是我的resize不能同时执行多次。以便我使用Array.prototype.forEach而不是async.forEach来期望每个文件都将被逐个处理。让exec函数里面forEach做一个一个的

var exec = require('child_process').exec; 

exec('ls ' + IMAGE_FOLDER, function (error, stdout, stderr) { 
    if (error) {throw error;} 
    var fileList = stdout.split("\n"); 
    fileList.pop(); //Remove the last element that null 
    fileList.forEach(function(imageFile, index, array) { 
     var inFile = IMAGE_FOLDER + imageFile; 
     console.log(inFile); 
     exec('resize ' + inFile, function(err, stdout, stderr){ 
      if (err) { 
       console.log(stderr); 
       throw err; 
      } 
      console.log('resized ' + imageFile); 
     }) 
    }); 
}); 

但我得到的结果是我的代码的行为是无块,它打印出:

image1 
image2 
... 
resized image1 
resized image2 
... 

我预期的打印输出的行为应该是:

image1 
resize image1 
image2 
resize image2 
... 

请告诉我我错在哪里。任何帮助是不同的欣赏。

+0

您是否找到解决方案?如果是,请张贴您的答案 –

+0

我做了替代解决方案,但我认为您可以尝试Jyotman Singh的以下建议。如果它有效,请留言。 –

回答

1

Array.prototype.forEach将同步执行您的JavaScript代码,无需等待异步函数完成,因此将在等待回调触发之前结束每个循环。

假设您知道async库,您应该使用async.series()方法。它会做你想要的。阅读有关它here

+0

但是我怎样才能遍历文件夹中的所有文件。 async.series()是函数的数组或对象。 –

+0

创建一个类似于上面使用'forEach'的方法的数组。在forEach中,只需按照'async.series'所需的格式将新函数推送到空数组。之后,只需将该数组提供给'async.series'。 –

+0

我会尝试与您的建议。非常感谢! –

相关问题