【问题标题】:Using "this" class context inside promise resolver在 Promise 解析器中使用“this”类上下文
【发布时间】:2018-04-02 16:33:40
【问题描述】:

是否可以将当前上下文 (this) 传递给 Promise 解析器?它似乎在解析器中被删除。

例子:

class A {
  constructor(someObject) {
    this.someObject = someObject;
  }

  foo() {
    return new Promise((resolve) => {
      this.someObject.doAsyncRequest(arg, function(val) { resolve(val); });
    });
  }
}

编辑:

错误将是: “无法读取一些未定义的对象”

编辑2: 抱歉,这确实有效。我在 webpack 中有一个错误,它会在提供文件之前将一些随机垃圾插入文件中。

【问题讨论】:

  • 这对我有用——你怎么称呼foo

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

这是一个更精简的版本,你所拥有的一切都很好:

class A {
  constructor() {
    this.a = "hello";
  }
  
  foo() {
     return new Promise(resolve => resolve(this.a));
  }
}

const a = new A();
a.foo().then(a => console.log(a));

由于您在 Promise 内使用箭头函数,因此会维护 this 上下文。

现在,如果你使用普通函数,你会丢失this,因为它会变得未定义(检查浏览器控制台,因为它会抛出错误,所以没有显示):

class A {
  constructor() {
    this.a = "hello";
  }
  
  foo() {
     return new Promise(function(resolve) { resolve(this.a) });
  }
}

const a = new A();
a.foo().then(a => console.log(a));

如果你想用它来维护上下文,你需要绑定它:

class A {
  constructor() {
    this.a = "hello";
  }
  
  foo() {
     return new Promise((function(resolve) { resolve(this.a) }).bind(this));
  }
}

const a = new A();
a.foo().then(a => console.log(a));

如果您使用foo() 作为回调,也可能会丢失上下文(再次检查浏览器控制台,因为它会引发错误):

class A {
  constructor() {
    this.a = "hello";
  }
  
  foo() {
     return new Promise(resolve => resolve(this.a));
  }
}

const a = new A();
const callback = a.foo;

callback().then(a => console.log(a));

要解决这个问题,请在将其用作回调之前绑定它:

class A {
  constructor() {
    this.a = "hello";
  }
  
  foo() {
     return new Promise(resolve => resolve(this.a));
  }
}

const a = new A();
const callback = a.foo.bind(a);
callback().then(a => console.log(a));

【讨论】:

  • 从什么时候开始"...您所拥有的工作正常" 是一个答案? O.o
  • “你所拥有的 [在你提供的具体示例中] 工作得很好,但这里有一些事情可能会在你的真实代码中发生”我相信这是一个不错的答案......跨度>
  • A.foo.bind(A) 的最后上瘾可能是 OP 的问题。但在他为我们提供一种复制他的问题的方法之前,我们无法确定。所以,猜测应该没问题。
  • 我想我涵盖了几乎所有的可能性。一种或另一种方式,没有进行适当的绑定。
  • @Federkun TO 使用箭头函数,因此.bind() 不会改变this
猜你喜欢
  • 2018-06-02
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 2016-08-12
相关资源
最近更新 更多