sumory
12/24/2012 - 7:16 AM

api.js

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 (ret.hasOwnProperty("b") && ret.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);
};