javascript - 使用 async.apply 时如何保持 this 的值?
问题描述
我正在使用 async.parallel 一次运行 2 个函数,这些函数是从 mongoose 模型上的静态函数运行的。如您所见,我可以this
访问模型及其代码中的函数(模型有一个名为 verifyParent 的静态函数):
async.parallel([
async.apply(content, {slug: slug}),
async.apply(this.verifyParent, req.body.reply),
], (err, result) => {
//results
});
但是在 this.verifyParent 函数中,如果我尝试使用this
,它等于我的 express 应用程序,而不是 mongoose 模型。我相信 async.apply 正在这样做,我不知道如何让它保持this
它通常具有的价值。
在 verifyParent 中,我正在尝试查询 mongodb。当我运行时this.findOne()
,它说它不是一个函数,并且看起来这似乎表明它设置了应用程序,而不是模型。
解决方案
您可以像这样将函数绑定到当前上下文,
async.parallel([
async.apply(content, {slug: slug}),
async.apply(this.verifyParent.bind(this), req.body.reply),
], (err, result) => {
//results
});
这是 async.apply 的函数定义,它似乎使用传递的参数调用传递的函数,这就是为什么this
设置为 express app 的父作用域的原因。
所以基本上正在发生的事情是这样的,
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))
推荐阅读
- java - 启用 Spring 安全性,不再提供默认登录页面或处理对“myserver/login”的请求
- r - lubridate 生成一个新的 NA 额外值
- flutter - 未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'siteId'
- java - 当我在 println 中添加“\n”时变量发生了变化
- php - 使用 PHP 如何将数组转换为用于 SQL 查询的项目字符串
- azure - 从 Azure 门户中的 Cosmos 集合中删除文档
- sql - 在 vb.net 中使用选择查询
- terraform - 尽管 cloud-init,Digital Ocean Droplet 不是最新的
- exchangewebservices - Microsoft Exchange Web Services 确保电子邮件发送成功
- amazon-web-services - 如何检索使用其标签过滤的 AWS IAM 角色详细信息