Skip to content

Instantly share code, notes, and snippets.

@joewalker
Created January 3, 2013 15:40
Show Gist options
  • Save joewalker/4444366 to your computer and use it in GitHub Desktop.
Save joewalker/4444366 to your computer and use it in GitHub Desktop.
// Promises:
// An alternative to using callback functions.
// An encapsulation for a callback function
// and an on-error function.
// A way of adding any number of callback
// and on-error handler_s_ (even after the event)
// ... that can look more (a bit) less weird
var sum = add(1, 2);
console.log("1 + 2 = ", sum);
var sumPromise = asyncAdd(1, 2);
var onDone = function(sum) {
console.log("1 + 2 = ", sum);
};
sumPromise.then(onDone);
asyncAdd(1, 2).then(function(sum) {
console.log("1 + 2 = ", sum);
});
// Error handling ...
try {
var sum = add(1, 2);
console.log("1 + 2 = ", sum);
}
catch (ex) {
console.error(ex);
}
// Error handling is more important
// because you'll lose the stack trace
var sumPromise = asyncAdd(1, 2);
var onDone = function(sum) {
console.log("1 + 2 = ", sum);
};
var onError = function(ex) {
console.error(ex);
};
sumPromise.then(onDone, onError);
var sumPromise = asyncAdd(1, 2);
sumPromise.then(function(sum) {
console.log("1 + 2 = ", sum);
}, function(ex) {
console.error(ex);
});
asyncAdd(1, 2).then(function(sum) {
console.log("1 + 2 = ", sum);
}, console.error);
// Chrome sucks
asyncAdd(1, 2).then(function(sum) {
console.log("1 + 2 = ", sum);
}, console.error.bind(console));
// History:
// * Common JS
// * Promises A/B/C
// * Node
// * Q
// * EcmaScript
// We can all agree that a promise is a thing
// - with a 'then' function
// - that takes 2 parameters,
// - a callback
// - and an error handler.
function asyncAdd(p1, p2) {
var deferred = Q.defer();
setTimeout(function() {
deferred.resolve(p1 + p2);
}, 500);
return deferred.promise;
}
Q.defer = function() {
return {
var observers = [];
promise: {
then: function(onDone, onError) {
observers.add({ onDone: onDone, onError: onError });
}
},
resolve: function(value) {
observers.forEach(function(observer) {
observer.onDone(value);
});
},
reject: function(err) {
observers.forEach(function(observer) {
observer.onError(err);
});
},
};
};
// toolkit/addon-sdk/promise/core.js
// Detecting Promises
if (typeof thing.then === 'function') { ... }
var onDone = function(value) { ... };
if (typeof thing.then === 'function') {
thing.then(onDone);
}
else {
onDone(thing);
}
Q.resolve(thing).then(onDone, onError);
Q.resolve(42).then(console.log);
// Q.all
var first = Q.resolve(1);
var second = Q.resolve(2);
first.then(function(v1) {
second.then(function(v2) {
console.log(v1, v2);
}
});
Q.all(first, second).then(function(values) {
console.log(values[0], values[1]);
});
// Q.promised
function add(x, y) { return x + y }
var asyncAdd = Q.promised(add);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment