Hedge
Hedge

Reputation: 16748

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

Upvotes: 2

Views: 516

Answers (2)

Marco Scabbiolo
Marco Scabbiolo

Reputation: 7449

By assigning an arrow function to createEntity, this inside the arrow function is assigned to the value of this in the scope where the arrow function was declared, which is probably the global object (therefore if you're using use strict, this will be undefined), and it'll stay that way even if you invoke the function using call.

Use a common function expression instead

createEntity: function () {
    ...
}

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816242

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

Upvotes: 4

Related Questions