1

Consider the following code:

var qq=$q(function(resolve, reject) {   
    setTimeout(function() {
        if (true) {
            console.log(qq);
            resolve('Hello!');
            console.log(qq);
        } else {
            ...
        }
    }, 5000);
});

console.log(qq);

There are three console.log commands. The last one is executed first and it correctly outputs a promise object with status 0. I was waiting for the first console.log inside setTimeout to output a promise object with pending status (0), since it stands before resolve. However, both of console.log commands inside setTimeout output a resolved promise with status 1. Could someone explain that to me?

Unknown developer
  • 4,620
  • 9
  • 34
  • 72
  • 2
    Console in browser always displays the current object state. Log it with JSON.stringify or log the promise status directly instead of the object – smnbbrv Nov 16 '16 at 16:59
  • 1
    Yup. The browser logs a reference to the object, but it can't write to the log until the script has yielded the CPU. The script ends (or yields the CPU some other way), and the log entries are resolved. –  Nov 16 '16 at 17:00
  • Can you post a screenshot, please? – Bergi Nov 16 '16 at 17:40
  • Have a look at [http://stackoverflow.com/q/33524696/1048572](http://stackoverflow.com/q/23392111/1048572), altough what you describe is a bit weirder. – Bergi Nov 16 '16 at 17:42
  • @Amy "*it can't write to the log until the script has yielded the CPU*" assumes single-threaded execution, for which there is no reason. The console likely lives in its own process. – Bergi Nov 16 '16 at 17:43
  • Don't forget that the JavaScript interpreter is single-threaded. –  Nov 16 '16 at 17:53

0 Answers0