Nodejs:Waterline + Caolan / Async:绑定函数

时间:2016-08-04 01:41:46

标签: javascript node.js asynchronous waterline

使用Balderdashy/WaterlineCaolan/Async,我试图并行化severa Waterline查询。到目前为止,我找到的时间越短越好:

const tasks = {
    foos: (function(){return this.exec.bind(this);}).apply(Foo.find({foo: "foo"})),
    bars: (function(){return this.exec.bind(this);}).apply(Bar.find({bar: "bar"}))
};
return async.parallel(tasks, function(err, out){
    // Here, err contains the potential error, and out looks like {foos:[...],bars:[...]}
});

我已尝试bars: Bar.find({bar: "bar"}).exec async apply似乎bars: function(cb){Bar.find({bar: "bar"}).exec(cb)} 该函数与另一个对象作为范围...所以我无法找到方法以更短/更简单的方式做到这一点。

请注意,我想避免自己将功能包装在另一个中,因为这是我想要找到替代方法的语法:

.expandAnimation{
    animation: expanding-opacity 4s infinite;
}

/* Expand */

@-moz-keyframes expanding-opacity {
    from { -moz-transform: scale(1);opacity:0.2; }
    to { -moz-transform: scale(12); opacity:0;}
}
@-webkit-keyframes expanding-opacity {
    from { -webkit-transform: scale(1);opacity:0.2; }
    to { -webkit-transform: scale(12); opacity:0;}
}
@keyframes expanding-opacity {
    from {transform:scale(1);opacity:0.2;}
    to {transform:scale(12);opacity:0;}
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

Waterline的Deferred是可以使用的,所以你可以而且应该将它们与promises一起使用。 bluebird是一个很好的实现。

return bluebird.props({
    foos: Foo.find({foo: "foo"}),
    bars: Bar.find({bar: "bar"})
}).then(function (out) {
    // …
});

是的,即使你想要回调一般。

return bluebird.props({
    foos: Foo.find({foo: "foo"}),
    bars: Bar.find({bar: "bar"})
}).asCallback(function (err, out) {
    // …
});

如果你有充分的理由不使用承诺,尽管Waterline已经使用过它们,我想你可以在Deferred原型附加一些东西:

var Deferred = require('waterline/lib/waterline/query/deferred').Deferred;

Object.defineProperty(Deferred.prototype, 'execBound', {
    configurable: true,
    get: function () {
        return this.exec.bind(this);
    }
});

用作:

const tasks = {
    foos: Foo.find({foo: "foo"}).execBound,
    bars: Bar.find({bar: "bar"}).execBound
};
return async.parallel(tasks, function(err, out){
    // Here, err contains the potential error, and out looks like {foos:[...],bars:[...]}
});
相关问题