让exec函数里面forEach做一个一个的

我遇到了nodejsasynchronous的问题。 我想调整文件夹中的图像大小, resize是一个可执行的二进制文件。 问题是我的resize不能同时执行多次。 所以我使用Array.prototype.forEach而不是async.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 ... 

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

Array.prototype.forEach将同步执行您的JavaScript代码,而不等待asynchronous函数完成,因此将在等待callback触发之前结束每个循环。

假设你了解async库,你应该使用async.series()方法。 它会做你想要的。 在这里阅读。