javascript, promises, how to access variable this inside a then scope [duplicate] – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and promise. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about javascript, promises, how to access variable this inside a then scope [duplicate].
Problem :
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)
})
Solution :
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);
});
}