Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) }) 
like image 333
GWorking Avatar asked Sep 13 '15 08:09

GWorking


People also ask

How can I access a variable outside a Promise then method?

You need to return the promise from the Spotify. getCurrentUser() , and then when you return names within that it is returned by the outer function.

What is the problem with promises in JavaScript?

Promises have an API which encourages casually dangerous code. Promises lack a convenient API to safely work with data. Promises co-mingle rejected promises and unintended runtime exceptions.

What is nested scope in JavaScript?

In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules. Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.

Do JavaScript promises run in parallel?

Promises cannot "be executed". They start their task when they are being created - they represent the results only - and you are executing everything in parallel even before passing them to Promise.


1 Answers

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);   }); }
like image 103
Andy Avatar answered Sep 22 '22 19:09

Andy