Permalink
Browse files

Added a "Lazy" constructor for wrapping promises for objects with kno…

…wn eventual types.
  • Loading branch information...
1 parent 9a3ac58 commit a0a3e31e786853b1a1249fc2fc34e7d045591602 Kristopher Kowal committed May 19, 2011
Showing with 40 additions and 0 deletions.
  1. +18 −0 qq.js
  2. +1 −0 test/all.js
  3. +21 −0 test/lazy.js
View
18 qq.js
@@ -312,6 +312,24 @@ function reduce(values, callback, accumulator, that) {
return reduction.promise;
}
+exports.Lazy = function (constructor, promise) {
+ var prototype = constructor.prototype;
+ var result = exports.defer();
+ result.resolve(promise);
+ var proxy = Object.create(result.promise);
+ while (prototype !== Object.prototype) {
+ Object.getOwnPropertyNames(prototype).forEach(function (name) {
+ if (typeof prototype[name] === "function") {
+ proxy[name] = function () {
+ return Q.post(result.promise, name, arguments);
+ };
+ }
+ });
+ prototype = Object.getPrototypeOf(prototype);
+ }
+ return proxy;
+};
+
// boilerplate that permits this module to be used as a
// <script> in less-than-ideal situations.
}).apply(this, typeof exports !== "undefined" ? [
View
@@ -1,5 +1,6 @@
exports['test deep'] = require('./deep');
+exports['test lazy'] = require('./lazy');
if (module == require.main)
require('test').run(exports)
View
@@ -0,0 +1,21 @@
+
+var Q = require('qq');
+
+exports['test Lazy'] = function (ASSERT, done) {
+ var inputs = [1,2,3];
+ var proxy = Q.Lazy(Array, Q.delay(1, inputs));
+ var results = [];
+ var ready = proxy.forEach(function (n) {
+ results.push(n);
+ });
+ Q.when(ready, function () {
+ ASSERT.deepEqual(results, inputs, 'forEach on Lazied Array');
+ }).then(done, function () {
+ ASSERT.ok(false);
+ done();
+ });;
+};
+
+if (module == require.main)
+ require('test').run(exports)
+

0 comments on commit a0a3e31

Please sign in to comment.