mirror of
https://github.com/mozilla/gecko-dev.git
synced 2025-02-03 20:49:27 +00:00
Bug 606695 - Helper for chaining async functions [r=mconnor]
This commit is contained in:
parent
3df95ee050
commit
e1a52f2169
@ -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
|
||||
*
|
||||
|
27
services/sync/tests/unit/test_utils_asyncChain.js
Normal file
27
services/sync/tests/unit/test_utils_asyncChain.js
Normal 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);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user