Last active
December 10, 2015 18:29
-
-
Save jaakkos/4475171 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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