Skip to content

Instantly share code, notes, and snippets.

@seckcoder
Forked from JacksonTian/api.js
Last active December 10, 2015 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seckcoder/4367391 to your computer and use it in GitHub Desktop.
Save seckcoder/4367391 to your computer and use it in GitHub Desktop.
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