第1章-安装Node.js及相关要点-1.6.优化Node.js中的回调函数

来源:互联网 发布:借助知乎对信仰的回答 编辑:程序博客网 时间:2024/05/29 11:42

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的方式进行替代,或者直接使用异步库也可以。

0 0
原创粉丝点击