【问题标题】:Javascript Function ChainingJavascript 函数链接
【发布时间】:2013-11-22 01:12:44
【问题描述】:

我经常看到这样的函数链:

db.find('where...')
.success(function(){...})
.error(function(error){...});

我正在为我的项目开发验证库,我想知道如何进行这样的链接。 问候

【问题讨论】:

    标签: javascript node.js chaining


    【解决方案1】:

    只需从函数调用中返回您正在操作的对象。

    function MyObject(x, y) {
        var self = this;
        self.x = x;
        self.y = y;
        return {
            moveLeft: function (amt) {
                self.x -= amt;
                return self;
            },
            moveRight: function (amt) {
                self.x += amt;
                return self;
            }
        }
    }
    var o = MyObject(0, 0);
    o.moveLeft(5).moveRight(3);
    

    【讨论】:

    • 在少数情况下,您会返回一个有意义的不同对象,例如 db.find() 可能会返回 ResultSet 之类的东西,但是,是的,通常只返回this.
    【解决方案2】:

    您所指的是Promise,这是一种用Javascript 处理异步函数的编程风格。更多信息在这里 http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt2-practical-use

    在您的特定情况下,您可以为此使用when。这是一些可以帮助您入门的示例代码

    function validateUnique() {
      var deferred = when.defer();
      db.query(...query to check uniqueness here.., function(error, result){
        // this is a normal callback-style function
        if (error) {
          deferred.reject(error);
        } else {
          deferred.resolve(result);
        }
      }
    
      return deferred.promise(); // return a Deferred object so that others can consume
    }
    

    用法

    validateUnique().done(function(result){
      // handle result here
    }, function(error){
      // handle error here
    })
    

    如果你想继续这个链条

    validateUnique().then(anotherValidateFunction)
                    .then(yetAnotherValidateFunction)
                    .done(function(result){}, function(error){})
    

    P/s:whenhttps://github.com/cujojs/when的链接

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多