Bug 606695 - Helper for chaining async functions [r=mconnor]

This commit is contained in:
Philipp von Weitershausen 2010-10-29 06:54:30 -07:00
parent 3df95ee050
commit e1a52f2169
2 changed files with 57 additions and 0 deletions

View File

@ -53,6 +53,36 @@ Cu.import("resource://services-sync/log4moz.js");
*/
let Utils = {
/**
* Execute an arbitrary number of asynchronous functions one after the
* other, passing the callback arguments on to the next one. All functions
* must take a callback function as their last argument. The 'this' object
* will be whatever asyncChain's is.
*
* @usage this._chain = Utils.asyncChain;
* this._chain(this.foo, this.bar, this.baz)(args, for, foo)
*
* This is equivalent to:
*
* let self = this;
* self.foo(args, for, foo, function (bars, args) {
* self.bar(bars, args, function (baz, params) {
* self.baz(baz, params);
* });
* });
*/
asyncChain: function asyncChain() {
let funcs = Array.slice(arguments);
let thisObj = this;
return function callback() {
if (funcs.length) {
let args = Array.slice(arguments).concat(callback);
let f = funcs.shift();
f.apply(thisObj, args);
}
};
},
/**
* Wrap a function to catch all exceptions and log them
*

View File

@ -0,0 +1,27 @@
Cu.import("resource://services-sync/util.js");
function run_test() {
_("Chain a few async methods, making sure the 'this' object is correct.");
let methods = {
save: function(x, callback) {
this.x = x;
callback(x);
},
addX: function(x, callback) {
callback(x + this.x);
},
double: function(x, callback) {
callback(x * 2);
},
neg: function(x, callback) {
callback(-x);
}
};
methods.chain = Utils.asyncChain;
// ((1 + 1 + 1) * (-1) + 1) * 2 + 1 = -3
methods.chain(methods.save, methods.addX, methods.addX, methods.neg,
methods.addX, methods.double, methods.addX, methods.save)(1);
do_check_eq(methods.x, -3);
}