CallBacks可以让Node.js代码异步执行,但是当不熟悉JavaScript的Java或者PHP开发人员看到回调Hell的Node.js代码时,肯定大吃一惊,
fs.readdir(source, function(err, files){
if(err){
console.log('Error finding files:' + err);
}else{
files.forEach(function(filename, fileIndex){
console.log(filename);
gm(source + filename).size(function(err, values){
if(err){
console.log('Error identifying file size:' + err);
}else{
console.log(filename + ':' + values);
asppect = (values.width/values.height);
widths.forEach(function(width, widthIndex){
height = Math.round(width/aspect);
console.log('resizing' + filename + 'to' + height + 'x' + height);
this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err){
if(err) console.log('Error writing file: ' + err);
})
}.bind(this))
}
})
})
}
})
当然,使用两个空格的缩进形式时,他看起来还可以。
然而我们要知道的是,回调代码可以用事件的emit或者promise的方式进行替代,或者直接使用异步库也可以。