Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Last active December 14, 2015 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juandopazo/5095574 to your computer and use it in GitHub Desktop.
Save juandopazo/5095574 to your computer and use it in GitHub Desktop.
ArrayPromise for array-like fun with YUI promises
function ArrayPromise() {
ArrayPromise.superclass.constructor.apply(this, arguments);
}
Y.extend(ArrayPromise, Y.Promise);
Y.Array.each(['each', 'map', 'filter', 'some', 'every', 'reject'], function (method) {
ArrayPromise.prototype[method] = function () {
var args = Array.prototype.slice.call(arguments);
return this.then(function (results) {
return Y.Array[method].apply(Y.Array, [results].concat(args));
});
};
});
var __batch = Y.batch;
Y.batch = function () {
var promise = __batch.apply(Y, arguments);
return new ArrayPromise(function (resolve, reject) {
promise.then(resolve, reject);
});
};
function async(args, fn) {
return Y.batch.apply(Y, Y.Array.map(args, function (arg) {
return new Y.Promise(function (resolve, reject) {
fn(arg, function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
});
}
async(['foo.php', 'bar.php', 'baz.php'], Y.io).filter(function (result) {
return result.indexOf('foo') > 1;
}).each(function (result) {
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment