Last active
December 14, 2015 13:48
-
-
Save juandopazo/5095574 to your computer and use it in GitHub Desktop.
ArrayPromise for array-like fun with YUI promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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