LoginSignup
22
21

More than 5 years have passed since last update.

node.jsでコールバックのネストを浅くする

Last updated at Posted at 2012-07-03
app.js
var fs = require('fs')
, path = '/tmp/fs.txt';

console.log('非同期処理です');
fs.writeFile(path, 'hello', function (error) {  //ファイルを作成
    fs.open(path, 'a', 0666, function (error, file) {   //ファイルをオープン
        fs.write(file, '\nworld', null, 'utf-8', function () { //ファイルに書き込み
            fs.close(file, function (error) {   //ファイルポインタをクローズ
                fs.readFile(path, 'utf-8', function (error, data) { //ファイル読み込み
                    console.log(data);  //コンソールに出力
                });
            });
        });
    });
});
console.log('こっちが先');

たとえばこんな処理。ネストが深くなってて読みづらい。
こんな時にフロー制御ライブラリを使うと、ネストを浅くできて可読性が増す。
とりあえず最も有名っぽいasyncを使う。

npm install async

インストール終わり。

async.js
async.waterfall([処理1, 処理2, 処理3], 処理が終了した時の処理);

処理1→処理2→処理3→処理が終了した時の処理
という順で実行される。

さっきのコードをasyncで書いてみる。

fsAsync.js
var fs = require('fs')
, async = require('async')
, path = '/tmp/fsAsync.txt';

console.log('非同期処理です');
async.waterfall(
    [
    function(callback) {
        //ファイルを作成
        fs.writeFile(path, 'hello', function(error, file){
            callback(null);
        });
    },
    function(callback) {
        //ファイルポインタを生成
        fs.open(path, 'a', 0666, function (error, file){
            callback(null, file);
        });
    },
    function (file, callback) {
        //書き込み
        fs.write(file, '\nworld', null, 'utf-8', function () {
            callback(null, file);
        });
    },
    function(file, callback) {
        //ファイルポインタをクローズ
        fs.close(file, function (error){
            callback(null);
        });
    },
    function(callback) {
        //ファイルの中身を読み込む
        fs.readFile(path, 'utf-8', function(error, data) {
            console.log(data);  //コンソールに出力
            callback(null);
        });
    }
    ], function (error) {
        console.log('終わり');
    });
console.log('終わりじゃない');

縦に長くなっただけではないかと思われるけど、可読性は向上している。たぶん。

22
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
21