0

I am trying to define a global variable c inside a setTimeout function where promise is involved.

I tried the following code based on the answer here. But this did not work!

This code involves asynchronous and I do understand that the function test is non-blocking for console.log(c) and that is why I received an "undefined" outcome. How may I solve this issue?

let k = new Promise((resolve, reject) => {
  if (2 < 4) {
    resolve('you are okay');
  } else {
    reject('You are not okay');
  }
});

var c;

function test() {
  setTimeout(() => {
    c = k.then(x => console.log(x,"x in then"));
     console.log(c,"in setTimeout")
  }, 2000);
}

test();

console.log(c,"outside");
mplungjan
  • 169,008
  • 28
  • 173
  • 236
rsc05
  • 3,626
  • 2
  • 36
  • 57
  • [Likely dupe](https://stackoverflow.com/questions/49938266/how-to-return-values-from-async-functions-using-async-await-from-function) which is a dupe of [this](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – mplungjan Oct 13 '21 at 11:50
  • @mplungjan I do not understand, how is this a duplicate. It is not. The question you referring me to is "How to return the response from an asynchronous call" which is not a global variable, no? – rsc05 Oct 13 '21 at 11:53
  • I said Likely dupe. Someone found a better dupe – mplungjan Oct 13 '21 at 12:01
  • @mplungjan does that mean we can not define a variable globally from the outside the setTimeout? – rsc05 Oct 13 '21 at 12:02
  • 2
    You can *define* the variable, the problem is the *timing* of when you're trying to read it and when it is actually set. mplungjan has updated your code to demonstrate that very well. – deceze Oct 13 '21 at 12:02

0 Answers0