Nodejs:Waterline + Caolan / Async:绑定函数
使用Balderdashy /水线和Caolan /asynchronous ,我试图平行severa水线查询。 到目前为止,我发现的更短的是:
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
该函数与另一个对象作为范围…所以我不能find一种方法来做到这一点更简单的方法。
请注意,我想避免将函数封装在另一个函数中,因为它是我想要查找替代方法的语法:
bars: function(cb){Bar.find({bar: "bar"}).exec(cb)}
感谢您的帮助。
水线的Deferred
是可以的,所以你可以也应该用承诺来使用它们。 蓝鸟是一个很好的实现。
return bluebird.props({ foos: Foo.find({foo: "foo"}), bars: Bar.find({bar: "bar"}) }).then(function (out) { // … });
是的,即使你想要一般的callback。
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:[...]} });