Skip to content

Instantly share code, notes, and snippets.

@jaakkos
Last active December 10, 2015 18:29
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 jaakkos/4475171 to your computer and use it in GitHub Desktop.
Save jaakkos/4475171 to your computer and use it in GitHub Desktop.
var find_out_meaning_of_life = function (is_it, callback) {
var meaning_of_life = 42;
try {
setTimeout(function () {
callback(null, (is_it === meaning_of_life))
}, 420);
} catch(err) {
callback(err, 'FAIL!');
}
};
var philosopher_say_it_loud = function (err, result) {
if (err) {
console.log(err);
} else {
if (result)
console.log('Heureka!', result);
else
console.log('Darn!');
}
};
find_out_meaning_of_life(41, philosopher_say_it_loud);
find_out_meaning_of_life(42, philosopher_say_it_loud);
// With events
var events = require('events');
function Philosopher() {
this.meaning_of_life = 42;
events.EventEmitter.call(this);
}
Philosopher.super_ = events.EventEmitter;
Philosopher.prototype = Object.create(events.EventEmitter.prototype, {
constructor: {
value: Philosopher,
enumerable: false
}
});
Philosopher.prototype.find_out_meaning_of_life = function(is_it) {
var self = this;
setTimeout(function () {
self.emit('result', is_it === self.meaning_of_life );
}, 420);
return self;
}
var aristoteles = new Philosopher();
aristoteles.on('result', function(result) {
if (result) {
console.log('Heureka!');
} else {
console.log('Darn...');
}
})
aristoteles.find_out_meaning_of_life(32);
aristoteles.find_out_meaning_of_life(42);
// with promise
// https://github.com/cujojs/when
var when = require('when');
var find_out_meaning_of_life = function (is_it) {
var deferred = when.defer();
var meaning_of_life = 42;
setTimeout(function () {
deferred.resolve((is_it === meaning_of_life));
}, 420);
return deferred.promise;
};
var philosopher_say_it_loud = function (result) {
if (result)
console.log('Heureka!');
else
console.log('Darn!');
};
find_out_meaning_of_life(41).then(philosopher_say_it_loud);
find_out_meaning_of_life(42).then(philosopher_say_it_loud);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment