How to keep the value of this when using async.apply? [duplicate]
From your question, this
is the model.
then you should change code to
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});
Because this
keyword is context based. See Function context for more.
You can just bind the function to current context like this,
async.parallel([ async.apply(content, {slug: slug}), async.apply(this.verifyParent.bind(this), req.body.reply), ], (err, result) => { //results});
This is the function definition of async.apply, which seems like it calls the passed function with passed arguments, that's why this
gets set to parent scope which is express app.
So basically what is happening is 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))
This can be done in the following ways:
Using arrow functions:
async.parallel([ async.apply(content, {slug: slug}), async.apply(() => this.verifyParent, req.body.reply), ], (err, result) => { //results});
Using hard binding:
...function boundedVerifyParent() { return this.verifyParent.call(this)}...async.apply(this.boundedVerifyParent, req.body.reply),...
Or using bind
method:
...async.apply(this.verifyParent.bind(this), req.body.reply),...