summaryrefslogtreecommitdiffstats
path: root/lib/utils/promise.js
diff options
context:
space:
mode:
authorSamy Pessé <samypesse@gmail.com>2016-02-26 09:41:26 +0100
committerSamy Pessé <samypesse@gmail.com>2016-02-26 09:41:26 +0100
commitd3d64f636c859f7f01a64f7774cf70bd8ccdc562 (patch)
tree4f7731f37c3a793d187b0ab1cd77680e69534c6c /lib/utils/promise.js
parent4cb9cbb5ae3aa8f9211ffa3ac5e3d34232c0ca4f (diff)
parenteef072693b17526347c37b66078a5059c71caa31 (diff)
downloadgitbook-d3d64f636c859f7f01a64f7774cf70bd8ccdc562.zip
gitbook-d3d64f636c859f7f01a64f7774cf70bd8ccdc562.tar.gz
gitbook-d3d64f636c859f7f01a64f7774cf70bd8ccdc562.tar.bz2
Merge pull request #1109 from GitbookIO/3.0.0
Version 3.0.0
Diffstat (limited to 'lib/utils/promise.js')
-rw-r--r--lib/utils/promise.js62
1 files changed, 62 insertions, 0 deletions
diff --git a/lib/utils/promise.js b/lib/utils/promise.js
new file mode 100644
index 0000000..d49cf27
--- /dev/null
+++ b/lib/utils/promise.js
@@ -0,0 +1,62 @@
+var Q = require('q');
+var _ = require('lodash');
+
+// Reduce an array to a promise
+function reduce(arr, iter, base) {
+ return _.reduce(arr, function(prev, elem, i) {
+ return prev.then(function(val) {
+ return iter(val, elem, i);
+ });
+ }, Q(base));
+}
+
+// Transform an array
+function serie(arr, iter, base) {
+ return reduce(arr, function(before, item, i) {
+ return Q(iter(item, i))
+ .then(function(r) {
+ before.push(r);
+ return before;
+ });
+ }, []);
+}
+
+// Iter over an array and return first result (not null)
+function some(arr, iter) {
+ return _.reduce(arr, function(prev, elem, i) {
+ return prev.then(function(val) {
+ if (val) return val;
+
+ return iter(elem, i);
+ });
+ }, Q());
+}
+
+// Map an array using an async (promised) iterator
+function map(arr, iter) {
+ return reduce(arr, function(prev, entry, i) {
+ return Q(iter(entry, i))
+ .then(function(out) {
+ prev.push(out);
+ return prev;
+ });
+ }, []);
+}
+
+// Wrap a fucntion in a promise
+function wrap(func) {
+ return _.wrap(func, function(_func) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return Q()
+ .then(function() {
+ return _func.apply(null, args);
+ });
+ });
+}
+
+module.exports = Q;
+module.exports.reduce = reduce;
+module.exports.map = map;
+module.exports.serie = serie;
+module.exports.some = some;
+module.exports.wrapfn = wrap;