gpt4 book ai didi

javascript - Node : Waterline + Caolan/Async: bind function

转载 作者:行者123 更新时间:2023-11-30 15:54:45 25 4
gpt4 key购买 nike

使用 Balderdashy/WaterlineCaolan/Async ,我正在尝试并行处理多个 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"}).execasync 似乎适用 以另一个对象作为作用域的函数...所以我找不到一种更短/更简单的方法来做到这一点。

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

bars: function(cb){Bar.find({bar: "bar"}).exec(cb)}

感谢您的帮助。

最佳答案

Waterline 的 Deferred 是 thenables,因此您可以并且应该将它们与 promise 一起使用。 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 已经在使用 promises 但你有充分的理由不能使用它们,我想你可以将一些东西附加到 Deferred 原型(prototype):

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:[...]}
});

关于javascript - Node : Waterline + Caolan/Async: bind function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com