Skip to content

Instantly share code, notes, and snippets.

@NateFerrero
Last active August 29, 2015 14:17
Show Gist options
  • Save NateFerrero/c88afb0415459f25ba6a to your computer and use it in GitHub Desktop.
Save NateFerrero/c88afb0415459f25ba6a to your computer and use it in GitHub Desktop.
Exploration into a batch() function for promises.
var number = function (num) {
return new Promise(function (resolve, reject) {
if (typeof num !== 'number') {
reject('invalid type');
}
setTimeout(function () { resolve(num); }, 2000);
});
};
var batch = function () {
var isError = false;
var promises = [];
Array.prototype.forEach.call(arguments, function (arg) {
if (isError) {
if (typeof arg !== 'function') {
throw new Error('batch(Error, ...) function not found following Error keyword');
}
Promise.all(promises).catch(arg);
promises = [];
isError = false;
}
else if (arg === Error) {
isError = true;
}
else if (typeof arg === 'function') {
if (promises.length === 1 && promises[0] instanceof Promise) {
promises = [
promises[0].then(
Function.prototype.call.bind(arg, null)
)
];
}
else {
promises = [
Promise.all(promises).then(
Function.prototype.apply.bind(arg, null)
)
];
}
}
else {
promises.push(arg);
}
});
}
batch(
// a batch accumulates promises until a handler function is provided
number(5),
// values don't have to be promises though
7,
function (x, y) { console.log('# adding ' + x + ' + ' + y + ' now'); return x + y; },
// promises are implicitly chained
function (x) { console.log('# result is ' + x); return x; },
// a batch always accumulates including the last function return value
number(9),
function (v, w) { console.log(v * w, 'should be', 108); },
// a batch is ready to handle any errors thrown along the way
number ('A'),
function (z) { console.log('I never make it to the screen, since A is not a number'); },
// this is the syntax to handle errors
Error, function (err) {
console.warn('Oh no! I caught an error:', err);
}
);
@NateFerrero
Copy link
Author

Thinking along the lines of this for angular etc:

batch(
    $http.get('/foo/bar'),
    $http.get('/bat/baz'),
    function (response1, response2) {
        $scope.value = [response1.data, response2.data];
        $scope.success = true;
    },
    Error, function (err) {
        $scope.success = false;
    }
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment