Skip to content

Instantly share code, notes, and snippets.

@franquis
Last active September 1, 2016 11:05
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 franquis/5b12a11b8f6006f55fb32694926f79ed to your computer and use it in GitHub Desktop.
Save franquis/5b12a11b8f6006f55fb32694926f79ed to your computer and use it in GitHub Desktop.
A try to implement event based flow in javascript
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var log = function(str){
var t = Date.now();
console.log(t + " " + str);
}
var Call = function (){
var _ = this;
this.promises = [];
this.connected = false;
this.on('remote.hangup', function (e){
this.connected = false;
log("Remote hangup : disconnected");
});
};
util.inherits(Call, EventEmitter);
Call.prototype.queue = function (promise)
{
this.promises.push(promise);
};
Call.prototype.make = function (number){
log("Connecting to " + number + "...");
var that = this;
var delay = parseInt(Math.random() * 1000);
var action = new Promise(function(resolve, reject){
setTimeout(function (){
log("Connected after " + delay + "ms");
that.connected = true;
that.uid = 12345;
resolve(true);
}, delay);
});
this.queue(action);
return this;
};
Call.prototype.wait = function (delay){
var action = new Promise(function (resolve, reject){
setTimeout(function (){
log("Waited for " + delay + "s");
resolve(true);
}, delay * 1000);
});
this.queue(action);
return this;
};
Call.prototype.hangup = function (){
var that = this;
Promise.all(this.promises).then(function(){
if(that.connected === true){
log("HangUp");
that.connected = false;
} else {
log("\t> NOT CONNECTED");
throw new Error("NOT CONNECTED");
}
});
return this;
};
Call.prototype.transfertTo = function (to){
var that = this;
Promise.all(this.promises).then(function(){
if(that.connected === true){
log("HangUp");
} else {
log("\t> NOT CONNECTED");
throw new Error("NOT CONNECTED");
}
var action = new Promise(function (resolve, reject){
log("Transfering #"+ that.uid+ " to " + to);
setTimeout(function (){
log("Transfered to " + to);
resolve(true);
}, 800);
});
that.queue(action);
});
return this;
};
Call.prototype.trigger = function (evt){
this.emit(evt);
};
var c = new Call();
c.make("4411223344")
.transfertTo("4433445566")
.wait(2)
.transfertTo("4415252499")
.wait(5)
.hangup();
setTimeout(function (){
c.trigger('remote.hangup');
}, 10000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment