0
    var myVar;    
    myModule.myFunction().then(function(data){
       myVar = data;     
    });
    console.log(myVar);

I have a module named myModule which exports a function myFunction with some promise. Now when I assign the data to myVar, and print it, it shows undefined. What will be the proper solution to achieve this result?

Tom
  • 1,387
  • 3
  • 19
  • 30
Krisalay
  • 75
  • 3
  • 9
  • You are declaring myVar as undefined. Then assigning some data to myVar but in the meantime console.loging myVar. Make sure that the console log gets executed after the myVar = data by putting the console.log into the .then function right after myVar = data **Also check that data is not undefined** – noa-dev Oct 04 '16 at 10:33
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ben Fortune Oct 04 '16 at 10:57
  • 1
    @BenFortune, did you even read my question? I have already done whatever that solution says, but after the promise is returned, my control is blocked within the "then" block. – Krisalay Oct 04 '16 at 11:03
  • Clearly you haven't read the solutions. Scroll down to the promise solution by Benjamin Gruenbaum which is almost identical to your problem. – Ben Fortune Oct 04 '16 at 11:30

3 Answers3

1

You may have to reconsider your structure, but to achieve what you're asking for is to have the console.log inside the promise.

 var myVar;    
    myModule.myFunction().then(function(data){
       myVar = data;  
       console.log(myVar);   
    });
petur
  • 1,366
  • 3
  • 21
  • 42
1

The code you have posted is not synchronous, so it is working correctly.

This is the flow of your code to give you a better understanding of what the code is actually doing.

// myVar is declared undefined
var myVar;
// you call console.log with undefined
console.log(myVar);
// sometime later .then is called
myModule.myFunction().then(function(data){
   // later you set the global variable to the data
   myVar = data;
   // at this point you can log the value of myVar 
});

In terms of returning something from an ajax call you can't do it synchronously, but you can chain another .then after it's returned.

myModule.myFunction().then(function(data){
   // do something with the data
   return data; 
})
.then(function(data){
   // do something else with the data
})

You can keep chaining then as long as you want, and there are more useful methods you can use for error handling, or calling promises in parallel or synchronously

synthet1c
  • 6,152
  • 2
  • 24
  • 39
0

Because then is asynchronous, console.log will be called before then, so at the time of the log, it is undefined.

This will give you the result you're after:

var myVar;    
myModule.myFunction().then(function(data){
    myVar = data; 
    console.log(myVar);  
});
James Monger
  • 10,181
  • 7
  • 62
  • 98