我正在使用 async.parallel 一次运行 2 个函数,这些函数是从猫鼬模型上的静态函数运行的。如您所见,我可以this
访问模型及其在此代码中的函数(该模型具有一个名为 verifyParent 的静态函数(:
async.parallel([
async.apply(content, {slug: slug}),
async.apply(this.verifyParent, req.body.reply),
], (err, result) => {
//results
});
但是在this.verifyParent函数中,如果我尝试使用this
,它等于我的快递应用程序,而不是猫鼬模型。我相信 async.apply 正在这样做,我不知道如何让它保持它通常具有的this
值。
在verifyParent中,我正在尝试查询mongodb。当我运行this.findOne()
时,它说它不是一个函数,看着这个似乎表明它设置了应用程序,而不是模型。
从你的问题来看,this
是模型。
然后你应该将代码更改为
var model = this;
var verify = function(reply) {
model.verifyParent(reply);
};
async.parallel([
async.apply(content, {slug: slug}),
async.apply(verify, req.body.reply),
], (err, result) => {
//results
});
因为this
关键字是基于上下文的。有关详细信息,请参阅函数上下文。
你可以像这样将函数绑定到当前上下文,
async.parallel([
async.apply(content, {slug: slug}),
async.apply(this.verifyParent.bind(this), req.body.reply),
], (err, result) => {
//results
});
这是 async.apply 的函数定义,它似乎使用传递的参数调用传递的函数,这就是为什么this
设置为父范围,即快速应用程序。
所以基本上正在发生的事情是这样的,
function apply(fn) {
return fn();
}
var model = {
prop: "world",
verifyParent: function () {
console.log("hello", this.prop)
}
}
// model context is lost.
apply(model.verifyParent)
// bind to model explicitly.
apply(model.verifyParent.bind(model))
这可以通过以下方式完成:
使用箭头函数:
async.parallel([
async.apply(content, {slug: slug}),
async.apply(() => this.verifyParent, req.body.reply),
], (err, result) => {
//results
});
使用硬绑定:
...
function boundedVerifyParent() {
return this.verifyParent.call(this)
}
...
async.apply(this.boundedVerifyParent, req.body.reply),
...
或使用bind
方法:
...
async.apply(this.verifyParent.bind(this), req.body.reply),
...