Last active
December 15, 2015 14:49
-
-
Save KOBA789/5277014 to your computer and use it in GitHub Desktop.
チェーンの途中でエラーが起きたら Abort するだけの関数。「でかいフロー制御モジュールとかめんどいんじゃ!」って人(俺)向け。昔の俺なら Function.prototype に生やしてたかもしれない。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function maybe (callback) { | |
| return function (f) { // then | |
| return function (err) { // actual callback | |
| if (err) { | |
| callback(err); | |
| } else { | |
| f.apply(this, Array.prototype.slice.call(arguments, 1)); | |
| } | |
| }; | |
| }; | |
| } | |
| // use case | |
| function before (callback) { | |
| fs.readFile('foo.txt', function (err, data) { | |
| if (err) { | |
| callback(err); | |
| return; | |
| } | |
| fs.writeFile('bar.txt', data, function (err) { | |
| if (err) { | |
| callback(err); | |
| return; | |
| } | |
| callback(null); | |
| }); | |
| }); | |
| } | |
| function after (callback) { | |
| var then = maybe(callback); | |
| fs.readFile('foo.txt', then(function (data) { | |
| fs.writeFile('bar.txt', data, then(function () { | |
| callback(null); | |
| })); | |
| })); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment