簡體   English   中英

按需鏈接方法

[英]Chaining methods on-demand

標題可能真的很糟糕,對此感到抱歉://
我有一個庫可以為我創建具有預定義功能的用戶。 現在通過做類似的事情起作用

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

我也有像這樣的包裝方法:

lib.createUser.WithBla(callback)

但是,一旦您想到各種組合等,自然就會招致大量方法。因此,我有兩個想法:

  1. 以某種方式使這些調用可鏈接,而不必進行大量的回調函數處理。 例如。 lib.createUser(callback).WithBla().WithBlub().WithWhatever()...
  2. 傳遞諸如lib.createUser({Bla:true, Blub:true}, callback)

但是,考慮到所有這些方法都是異步的並且使用回調(我無法更改,因為它們基於節點模塊請求),我絲毫沒有絲毫線索。

也許不是您想的那樣,但是您可以為此使用異步庫。

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;
    );
});

結果是單個回調,而不是很多嵌套的回調。

另一種選擇是重新編寫代碼以使用Promises

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM