Javascript函数链接

时间:2013-11-22 01:12:45

标签: javascript node.js chaining

我经常看到这样的功能链:

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

我正在为我的项目开发验证库,我想知道我该怎么做这样的链接。 问候

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

您所指的是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:when https://github.com/cujojs/when

的链接
相关问题