Skip to content

Commit

Permalink
Added a "Lazy" constructor for wrapping promises for objects with kno…
Browse files Browse the repository at this point in the history
…wn eventual types.
  • Loading branch information
Kristopher Kowal committed May 19, 2011
1 parent 9a3ac58 commit a0a3e31
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions qq.js
Expand Up @@ -312,6 +312,24 @@ function reduce(values, callback, accumulator, that) {
return reduction.promise; 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 // boilerplate that permits this module to be used as a
// <script> in less-than-ideal situations. // <script> in less-than-ideal situations.
}).apply(this, typeof exports !== "undefined" ? [ }).apply(this, typeof exports !== "undefined" ? [
Expand Down
1 change: 1 addition & 0 deletions test/all.js
@@ -1,5 +1,6 @@


exports['test deep'] = require('./deep'); exports['test deep'] = require('./deep');
exports['test lazy'] = require('./lazy');


if (module == require.main) if (module == require.main)
require('test').run(exports) require('test').run(exports)
Expand Down
21 changes: 21 additions & 0 deletions test/lazy.js
@@ -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.