Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  67] [ 6]  / answers: 1 / hits: 76205  / 9 Years ago, sun, september 13, 2015, 12:00:00

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

More From » promise

 Answers
115

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




[#65085] Thursday, September 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;