简体   繁体   English

按需链接方法

[英]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) 传递诸如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 . 另一种选择是重新编写代码以使用Promises

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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