-
-
Save seckcoder/4367391 to your computer and use it in GitHub Desktop.
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
var events = require('events'); | |
var callA = function (callback) { | |
setTimeout(function () { | |
callback({name: "a", data: "I am result A"}); | |
}, Math.round(Math.random() * 300)); | |
}; | |
var callB = function (callback) { | |
setTimeout(function () { | |
callback({name: "b", data: Math.round(Math.random() * 300) % 2 === 0}); | |
}, Math.round(Math.random() * 300)); | |
}; | |
var callC = function (callback) { | |
setTimeout(function () { | |
callback({name: "c", data: "I am result C"}); | |
}, Math.round(Math.random() * 300)); | |
}; | |
var api = function (callback) { | |
var result = {}, counter = 0, timer; | |
var emitter = new events.EventEmitter(); | |
var done = function () { | |
clearTimeout(timer); | |
emitter.removeAllListeners(); | |
if (result.hasOwnProperty("b") && result.b) { | |
callC(function (c) { | |
result[c.name] = c.data; | |
callback(result); | |
}); | |
} else { | |
callback(result); | |
} | |
}; | |
var emit = function (ret) { | |
emitter.emit('got', ret); | |
}; | |
emitter.on('got', function (ret) { | |
result[ret.name] = ret.data; | |
counter++; | |
if (counter === 2) { | |
done(); | |
} | |
}); | |
callA(emit); | |
callB(emit); | |
timer = setTimeout(function () { | |
if (!result.hasOwnProperty('a')) { | |
emitter.on('got', function (ret) { | |
if (ret.name === 'a') { | |
done(); | |
} | |
}); | |
} else { | |
done(); | |
} | |
}, 200); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment