Reputation: 75
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?
Upvotes: 0
Views: 74
Reputation: 6282
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
Upvotes: 1
Reputation: 10665
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);
});
Upvotes: 0
Reputation: 1386
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);
});
Upvotes: 1