2

There will be for sure a duplicate for this question, but I'd like to have an answer for this specific piece of code. I have this function:

var somevar = ""; 
some.method({
    ...
}).then(function (data) {
    somevar = "Hello";
}).catch(function (error) {
    somevar = "Error";
});

console.log(somevar);

And at the end it will always print an empty string instead of the values that I'm trying to assign (for sure the program is going in the "then" or "catch" code block). Why this is happening? It seems to be a stupid question, but actually sometimes I have these kind of problems. I know how this stuff works (hoisting, scopes, assignment etc.) but sometimes I find myself in troubles and so I decided to ask here once and for all.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Giacomo Cerquone
  • 2,352
  • 5
  • 24
  • 33
  • 2
    This has nothing to do with scope. The functions you pass to `then` and `catch` are called *when an event fires*. That event doesn't fire until *after* the `console.log` line is executed. – Quentin Nov 04 '15 at 10:57
  • You need a deferred to wait the asynchronous calls to being executed. If you put `console.log()` inside the `them()` you can view that variable changes its value – Marcos Pérez Gude Nov 04 '15 at 11:00
  • @MarcosPérezGude Ok so now I understand. The problem is that I already applied that solution (repeating console.log inside "then" and "catch"). But I was trying to understand how to solve this thing withot repeating the console.log command two times! PS=are there some good articles in the web that can help me to understand the flow of the execution of a javascript script? – Giacomo Cerquone Nov 04 '15 at 11:16
  • Maybe you can see Deferred or Promise object from jQuery: https://api.jquery.com/promise/ | https://api.jquery.com/deferred.promise/ | https://api.jquery.com/category/deferred-object/ . With that, you can wait to finish a call and when the response is ready promise object is available to play with it. See first link, that example is really good. – Marcos Pérez Gude Nov 04 '15 at 11:28
  • I found very very useful this answer http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Giacomo Cerquone Nov 04 '15 at 12:56

0 Answers0