[英]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)
但是,一旦您想到各种组合等,自然就会招致大量方法。因此,我有两个想法:
lib.createUser(callback).WithBla().WithBlub().WithWhatever()...
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.