Created
December 17, 2015 16:53
-
-
Save nexpr/612f347a93224b296832 to your computer and use it in GitHub Desktop.
非同期あり関数を見分けれるようにする
This file contains 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 AFunc(fn){ | |
if(typeof fn !== "function") throw new TypeError(); | |
fn.__proto__ = AFunc.prototype | |
return fn | |
} | |
AFunc.prototype.__proto__ = Function.prototype | |
// こういうことができるようになる | |
function executor(fn){ | |
fn instanceof AFunc ? fn(next) : next(fn()) | |
} | |
// 使える例 | |
var aexecutor = { | |
_queue: [], | |
do: function(val){ | |
var fn = this._queue.shift() | |
fn && (fn instanceof AFunc ? fn(this.do.bind(this), val) : this.do(fn(val))) | |
}, | |
add: function(fn){ | |
this._queue.push(fn) | |
} | |
} | |
aexecutor.add(function(){console.log(1);return 2;}) | |
aexecutor.add(function(v){console.log(v,2);return 1+v;}) | |
aexecutor.do() | |
// 1 | |
// 2 2 | |
aexecutor.add(AFunc(function(){console.log(1);return 2;})) | |
aexecutor.add(function(v){console.log(v,2);return 1+v;}) | |
aexecutor.do() | |
// 1 | |
aexecutor.add(AFunc(function(next){console.log(1);next(2);})) | |
aexecutor.add(function(v){console.log(v,2);return 1+v;}) | |
aexecutor.do() | |
// 1 | |
// 2 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment