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

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)
});

Update: use an arrow function – they borrow the context (this) from their outer scope.

function two() {
  console.log('Done');
}

one().then(() => {
  this.two();
});

function one() {
  return new Promise(res => {
    setTimeout(() => res(), 2000);
  });
}

Leave a Comment

tech