0

I have a promise/global object that outputs as follows in the console:

console.log(globalInfo);

Promise
__proto__:Promise
    [[PromiseStatus]]:"resolved"
    [[PromiseValue]]:globalInfo
        item1:"12345"
        item2:"something else"
        item3:"www.stackoverflow.com"
        __proto__:Object

And am successfully pulling out the value for "item2" as such:

globalInfo.then(function(val) {
  newVar = val.item2;
  console.log('newVar inside: ' + newVar);
});
console.log('newVar outside: ' + newVar);

But, I am not able to pass that variable/value outside of the then() function. Nothing outputs to the console for the second console.log ("newVar outside").

How do I make the variable "newVar" with the the value for "item2" available globally outside of the then() function?

david
  • 243
  • 3
  • 17
  • 3
    asynchronous code is asynchronous ... there's no way to "fudge" the code to make that work like that – Jaromanda X Feb 15 '17 at 01:35
  • This seems like a duplicate of "how do I return for a asynchronous callback"? – Carcigenicate Feb 15 '17 at 01:35
  • http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron or http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – epascarello Feb 15 '17 at 01:36
  • 1
    The logic is supposed to live inside of the then. You can not do it outside. You basically are ordering a pizza on the phone and as soon as you make the call you try to eat the pizza. It is not going to happen because the pizza needs to be made and delivered. That is what the promise is doing. It is waiting for the doorbell to ring. You need to wait, so break up your code so it can be called when the pizza is delivered. – epascarello Feb 15 '17 at 01:41

0 Answers0