Skip to content

Instantly share code, notes, and snippets.

@JacksonTian
Last active December 10, 2015 02:08
Show Gist options
  • Save JacksonTian/4364823 to your computer and use it in GitHub Desktop.
Save JacksonTian/4364823 to your computer and use it in GitHub Desktop.
https://gist.github.com/4362563 EventProxy版本,勉强挤进50行
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);
};
@leizongmin
Copy link

俺也来个不依赖任何模块的版本,大概也是50行。只是代码难看了点

function sleep (s, callback) {
  setTimeout(callback, s * 1000);
}

function call_a (callback) {
  sleep(.1, function () {
    callback('a');
  });
}

function call_b (callback) {
  sleep(Math.random() * .3, function () {
    callback('b');
  });
}

// 调用此函数,按要求返回a,b的结果
function call (callback) {
  var retA = null, retB = null, isReturn = false;

  function checkDone (isNotTimeout) {
    if (isReturn) return;
    if (isNotTimeout) {
      if (retA !== null) {
        isReturn = true;
        callback(retA, retB);
      }
    } else {
      isReturn = true;
      callback(retA, retB);
    }
  }

  call_a(function (ret) {
    retA = ret;
    checkDone(true);
  });

  call_b(function (ret) {
    retB = ret;
    checkDone(true);
  });

  sleep(5, checkDone);
};

// 开始测试
var start = Date.now();
call(function (a, b) {
  var end = Date.now();
  console.log((end - start) + 'ms', a, b);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment