Created
April 22, 2015 20:17
-
-
Save fortruce/8cc8f77e08d2a50762d6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Promise = require('bluebird'); | |
function Micro (id) { | |
this.id = id; | |
} | |
Micro.prototype.connect = function () { | |
return new Promise(function (fulfill, reject) { | |
setTimeout(function() { | |
if (Math.random() > 0.5) | |
fulfill(this.id); | |
else | |
reject(new Error('failed')); | |
}.bind(this), 1000); // Note the bind calls to provide 'this' to the nested callbacks | |
}.bind(this)); // Otherwise, this.id would be undefined in the setTimeout callback | |
// where you would expect it to be 100 | |
} | |
// | |
// | |
var mc = new Micro(100); | |
mc.connect() | |
.then(console.log) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment