[英]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. 我不明白为什么在
const body = ctx.request.body
ctx变得不确定。 Before it carried over this
from the create()
function which calls createEntity()
. 之前,它延续
this
从create()
它调用函数createEntity()
What am I doing wrong? 我究竟做错了什么?
I'm calling a function createEntity
like this: 我正在这样调用函数
createEntity
:
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()
. create()
调用createEntity()
。 It is a generator function wrapped with co()
via Koa.js 这是一个通过Koa.js用
co()
包装的生成器函数
create: function * () {
this.body = yield createEntity.call(this)
}
EDIT: Here's a screenshot why I thought this
is fine after calling createEntity
: 编辑:下面是截图为什么我认为
this
是打完电话后精createEntity
:
both ctx and this are fine
ctx和这都很好
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 . 您无法通过
call
设置箭头函数的this
,因为箭头本身没有this
1 。
Use a normal function instead. 请改用普通功能。
See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? 另请参见Arrow函数与函数声明/表达式:它们是否等效/可互换?
1: this
inside createEntity
refers to the top-level this
of the module, which is module.exports
: 1:
createEntity
内部的this
指模块的顶层this
,即module.exports
:
this; // <------------|
module.exports = { |
createEntity: () => { |
var ctx = this // ---|
}
}
console.log(this === module.exports); // true
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
. 通过分配箭头功能
createEntity
, this
箭头函数内部分配给的值this
在范围,其中被宣布为箭头的功能,这可能是全局对象(因此,如果您正在使用use strict
, this
将是undefined
),即使您使用call
调用该函数,它也会保持这种状态。
Use a common function expression instead 改用通用函数表达式
createEntity: function () {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.