简体   繁体   中英

Chaining methods on-demand

The title is probably really bad, so sorry for that :/
I have a library that creates users for me with predefined capabilities. Right now that works by doing something like

var User = require(...).User;
var user = new User(...);
// user has methods like which are all asymc
user.register(callback);
user.addBla(callback);

I also have wrapper methods which work like:

lib.createUser.WithBla(callback)

however, that naturally does incur a huge number of methods once you think of various combinations etc. So I have two ideas:

  1. somehow make those calls chain-able without having to do huge levels of callback-function-juggling. eg. lib.createUser(callback).WithBla().WithBlub().WithWhatever()...
  2. passing some sort of capabilities like lib.createUser({Bla:true, Blub:true}, callback)

however I have not the slightest clue how to actually implement that, considering all those methods are asynchronous and use callbacks (which I cannot change, as they are based on the node-module request).

Maybe not quite what you had in mind, but you could use the library async for this.

var user = new User();
user.addSomeValue = function(someValue, cb) { cb(null) }

// Execute some functions in series (one after another)
async.series([
    // These two will get a callback as their first (and only) argument.
    user.register,
    user.addBla,

    // If you need to pass variables to the function, you can use a closure:
    function(cb) { user.addSomeValue(someValue, cb); }

    // Or use .bind(). Be sure not to forget the first param ('this').
    user.addSomeValue(user, someValue)
], function(err, results) {
    if(err) throw "One of the functions failed!";
    console.log(
        "The the various functions gave these values to the callbacks:",
        results;
    );
});

The result is a single callback, not many nested ones.

Another option would be to re-write your code to use Promises .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM