apoorvnarang apoorvnarang - 2 years ago 73
Javascript Question

Change outer variable value inside library call

I want to change the value of a variable which I'm calling in a library but it seems like due to some scope issue, I am not able to. My code looks like this:

var data = "";
abc.abc(lat, long).then(function(x) {
data = x;

The first output shows the value of x but the second output is still empty. What am I doing wrong?

Note: abc is an external library which uses promises.

Answer Source

You can't refer to the value of data before it is assigned. Even though the inner function(x) is declared before the second console.log it is called after.

See a simplified illustration of time each statement is executed labeled next to the code, starting with time = 0

var data = ""; // time = 0
abc.abc(lat, long).then(function(x) {
    data = x; // time = N > 2 (i.e. at this time, the promise has been resolved)
}); // time = 1
console.log(data); // time = 2

Bottom line, if you Could refer to data synchronously this way then don't use a promise. However, not using promises for potentially long-running operations is NOT recommended.

You should adopt your code such that any Access to data happens only after the promise is resolved.

The best practice for doing so may differ according to the Javascript framework you are using (if any)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download