Last active
December 10, 2015 02:08
-
-
Save JacksonTian/4364823 to your computer and use it in GitHub Desktop.
https://gist.github.com/4362563 EventProxy版本,勉强挤进50行
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
var callA = function (callback) { | |
setTimeout(function () { | |
callback(null, {name: "a", data: "I am result A"}); | |
}, Math.round(Math.random() * 300)); | |
}; | |
var callB = function (callback) { | |
setTimeout(function () { | |
callback(null, {name: "b", data: Math.round(Math.random() * 300)) % 2 === 0}); | |
}, Math.round(Math.random() * 300)); | |
}; | |
var callC = function (callback) { | |
setTimeout(function () { | |
callback(null, {name: "c", data: "I am result C"}); | |
}, Math.round(Math.random() * 300)); | |
}; | |
var api = function (callback) { | |
var result = {}, start = new Date().getTime(); | |
var emitter = new EventProxy(); | |
var done = function () { | |
emitter.removeAllListeners(); | |
callback(result); | |
}; | |
emitter.on('all', function (event, ret) { | |
result[ret.name] = ret.data; | |
}); | |
callA(function (a) { | |
emitter.emit('a', a); | |
// 200ms后,不管b了 | |
if (new Date().getTime() - start > 200) { | |
done(); | |
} | |
}); | |
callB(function (err, b) { | |
// 检查b的返回值 | |
if (b.hasOwnProperty("b") && b.data) { | |
callC(function (err, c) { | |
emitter.emit('c', c); | |
emitter.emit('b', b); | |
}); | |
} else { | |
emitter.emit('b', b); | |
} | |
}); | |
// a, b在200ms前完成的case | |
emitter.all('a', 'b', done); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
俺也来个不依赖任何模块的版本,大概也是50行。只是代码难看了点