Hedge Hedge - 4 months ago 8
Node.js Question

var becomes undefined inside Promise

This is probably something a very small problem but I can't find its solution so please bear with me!

I don't understand why at

const body = ctx.request.body
ctx becomes undefined. Before it carried over
this
from the
create()
function which calls
createEntity()
.

What am I doing wrong?

I'm calling a function
createEntity
like this:

module.exports = {
createEntity: () => {
var ctx = this // both ctx and this are fine
return new Promise((resolve, reject) => {
const body = ctx.request.body // <-- ctx is undefined
resolve();
})
}
}


create()
calls
createEntity()
. It is a generator function wrapped with
co()
via Koa.js

create: function * () {
this.body = yield createEntity.call(this)
}


EDIT: Here's a screenshot why I thought
this
is fine after calling
createEntity
:
enter image description here

Answer

both ctx and this are fine

I doubt that. You are using an arrow function. You cannot set an arrow function's this via call because an arrow doesn't have an own this 1.

Use a normal function instead.

See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?


1: this inside createEntity refers to the top-level this of the module, which is module.exports:

this;        // <------------|
module.exports = {           |
  createEntity: () => {      |
    var ctx = this     // ---|
  }
}
console.log(this === module.exports); // true
Comments