Created
October 26, 2010 02:17
-
-
Save coolaj86/646206 to your computer and use it in GitHub Desktop.
Promises/KISS example
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 Promise = require('futures'); | |
function getUnavailableData(params) { | |
var p = Promise.create({ updatable: true, timeout: Infinity, freeze: false }); | |
// p.fulfill(err, data, data, ...); | |
setInterval(askUserHowHeFeelsAboutLife, 60*60*1000, p.fulfill); | |
return p.protected(); // returns a different object which has no fulfill method | |
} | |
function useUnavailabledata() { | |
var p = getUnavailableData(); | |
if (! (p instanceof Promise)) { | |
throw new Error("How odd, not a promise instance"); | |
} | |
if ('function' !== typeof p.when) { | |
throw new Error("How odd, not a promise by duck-typing"); | |
} | |
p.when(function (err, data, data, ...) { | |
// store data in cache | |
}); | |
if (p.options.updatable) { | |
p.whenever(function (err, data, data, ...) { | |
// update data in cache | |
}); | |
} | |
p.ready // true once resolved | |
} | |
var j = Promise.join(options); | |
j.add(p1, p2, p3); | |
or | |
j.add([p1, p2, p3]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment