javascript, promises, how to access variable this inside a then scope [duplicate]

自作多情 提交于 2019-11-27 01:27:53

问题


This question already has an answer here:

  • Object method with ES6 / Bluebird promises 2 answers

I want to be able to call a function inside the .then scope, and for that I use the this.foo() manner. But if I do this inside the .then I get an error, since this appears to be lost. What can I do?

In this code, this would be equivalent to have the same output for the object this

console.log(this)
one().then(function() {
  console.log(this)
})

function one() {
  var deferred = $q.defer();
  deferred.resolve()
  return deferred.promise;
}

This neither seems to work

console.log(this)
var a = this;
one().then(function(a) {
  console.log(a)
})

回答1:


Your second code example is the right way to go. Because the scope changes in the new function, this changes too, so you're right to make a reference to this outside of the function.

The reason it failed is because the function is using a that you passed into the function rather than the global a you defined outside it.

In other words:

var a = this;
one().then(function () {
  console.log(a)
});


来源:https://stackoverflow.com/questions/32547735/javascript-promises-how-to-access-variable-this-inside-a-then-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!