首页 > 解决方案 > 使用 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(),它说它不是一个函数,并且看起来这似乎表明它设置了应用程序,而不是模型。

标签: javascriptexpressmongoosemongoose-schemaasync.js

解决方案


您可以像这样将函数绑定到当前上下文,

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))


推荐阅读