Skip to content

Instantly share code, notes, and snippets.

@ThisIsMissEm
Created February 3, 2010 13:12
Show Gist options
  • Save ThisIsMissEm/293591 to your computer and use it in GitHub Desktop.
Save ThisIsMissEm/293591 to your computer and use it in GitHub Desktop.
<!DOCTYPE HTML>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Promise</title>
<script src="http://o.aolcdn.com/dojo/1.4/dojo/dojo.xd.js">
</script>
<script type="text/javascript">
dojo.provide("dojox.Promise");
/*****************/
/* dojox.Promise */
/*****************/
dojox._promiseId = 0;
dojox.Promise = function(){
var topic = dojox._promiseId++;
return {
_topic: topic,
emit: function(data){
if(data){
console.log('Emitting on #'+topic+': '+data.toString());
}
dojo.publish('/dojox/Promise/'+topic,[data||null]);
},
then: function(doneHandler,errHandler){
var promise = dojox.Promise();
dojo.subscribe('/dojox/Promise/'+topic, function(data){
if(doneHandler && !(data instanceof Error)){
var res = doneHandler(data);
promise.emit(res);
}
if(errHandler && (data instanceof Error)){
errHandler(data);
promise.emit(data);
}
});
// lets write sth to the console so we can see when things happen.
console.log('Promise #'+topic+' returns new Promise #'+this._topic);
return promise;
}
}
};
/***********/
/* tests */
/***********/
var asyncComputeTheAnswerToEverything = function(){
var promise = new dojox.Promise();
console.log('initial function called');
window.setTimeout(function(){
// ok, we have success here, but it takes some time to compute
//var data = {id: 'someId', prop: 'someProp', tehAnswer: 42};
var data = 42;
console.log("initial function emitted");
promise.emit(data);
},2000);
console.log('initial function returns a promise');
return promise;
};
var addTwo = function(num){
if(Math.random() < 0.5) { // every now and then we throw an Error...
return new Error("Sorry, I couldn't compute teh answer.");
}
return num + 2;
};
var printResult = function(res){
console.info('teh result: ',res);
};
var onError = function(res){
console.error('Oopsie, an Error occurred: ',res);
};
/* run the example from the specs */
function testSpec(){
asyncComputeTheAnswerToEverything().
then(addTwo).
then(printResult, onError);
}
</script>
</head><body>
<p>Open the console and run <code>testSpec();</code> and see the source
of this file.</p>
<fieldset>
<legend>The promise code:</legend>
<pre> dojox.getPromiseId = function(){
if(!dojox._promiseId){
dojox._promiseId = 0;
}
return dojox._promiseId++;
};
dojox.Promise = function(currentTopicNo){
var topicNo = dojox.getPromiseId();
return {
then: function(doneHandler,errHandler){
dojo.subscribe('/dojox/Promise/'+currentTopicNo, function(data){
if(doneHandler &amp;&amp; !(data instanceof Error)){
var res = doneHandler(data);
dojo.publish('/dojox/Promise/'+topicNo,[res]);
}
if(errHandler &amp;&amp; (data instanceof Error)){
errHandler(data);
dojo.publish('/dojox/Promise/'+topicNo,[data]); // we hand over the same Error object
}
});
return new dojox.Promise(topicNo);
}
}
};
dojox.Promise.prototype.touched = 1;
</pre>
</fieldset>
</body><script id="_firebugCommandLineInjector" type="text/javascript">/* See license.txt for terms of usage */
var _FirebugCommandLine =
{
initFirebugCommandLine: function()
{
// Define console functions.
var commands = ["$", "$$", "$x", "$n", "cd", "clear", "inspect", "keys",
"values", "debug", "undebug", "monitor", "unmonitor", "traceCalls", "untraceCalls",
"traceAll", "untraceAll", "monitorEvents", "unmonitorEvents", "profile", "profileEnd", "copy"];
for (var i=0; i<commands.length; i++)
{
var command = commands[i];
// If the method is already defined, don't override it.
if (window[command])
continue;
this[command] = new Function(
"return window.console.notifyFirebug(arguments, '" + command + "', 'firebugExecuteCommand');");
}
// Define console shortcuts
var consoleShortcuts = ["dir", "dirxml"];
for (var i=0; i<consoleShortcuts.length; i++)
{
var command = consoleShortcuts[i];
this[command] = new Function("return window.console." + command + ".apply(window.console, arguments)");
}
// Define console variables.
var props = ["$0", "$1"];
for (var j=0; j<props.length; j++)
{
var prop = props[j];
if (window[prop])
continue;
this.__defineGetter__(prop, new Function(
"return window.console.notifyFirebug(arguments, '" + prop + "', 'firebugExecuteCommand');"));
}
this.attachCommandLine();
},
attachCommandLine: function()
{
// DBG window.dump("attachCommandLine "+window.location+"\n");
if (!window.console)
{
// DBG debugger;
window.loadFirebugConsole();
}
var element = window.console.getFirebugElement();
var self = this;
element.addEventListener("firebugCommandLine", function _firebugEvalEvent(event)
{
// DBG window.dump("attachCommandLine firebugCommandLine "+window.location+"\n");
var element = event.target;
var expr = element.getAttribute("expr"); // see commandLine.js
self.evaluate(expr);
// DBG window.dump("attachCommandLine did evaluate on "+expr+"\n");
}, true);
element.setAttribute("firebugCommandLineAttached", "true")
// DBG window.dump("Added listener for firebugCommandLine event "+window.location+"\n");
},
evaluate: function(expr)
{
try
{
var result = window.eval(expr);
if (typeof result != "undefined")
window.console.notifyFirebug([result], "evaluated", "firebugAppendConsole");
}
catch(exc)
{
var result = exc;
result.source = expr;
window.console.notifyFirebug([result], "evaluateError", "firebugAppendConsole");
}
},
};
(function()
{
try
{
// DBG window.dump("_FirebugCommandLine init console is "+window.console+" in "+window.location+"\n");
_FirebugCommandLine.initFirebugCommandLine();
}
catch(exc)
{
var wrappedException = {
cause: exc,
message: "_FirebugCommandLine init failed in "+window.location+" because "+exc,
toString: function() { return this.message; }
};
throw wrappedException;
}
})();
</script></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment