0

Javascript promises are giving me some unexpected behavior where they output in a synchronous and expected way when debugging with breakpoints but appear to be doing something strange and asynchronous when running otherwise. Here is my code:

jsfiddle link

function aPromise() {
    return new Promise(function(resolve, reject) {
      console.log("making a promise")
      bPromise().then(function() {
        console.log("resolving a promise")
        resolve();
      });
  });
}


function bPromise() {
    return new Promise(function(resolve, reject) {
        console.log("making b promise")

        console.log("resolving b promise")
        resolve();

  });
}

function logDone() {
    console.log("done");
}

aPromise().then(logDone)
aPromise().then(logDone)

The output to console of the above is this:

making a promise 
making b promise 
resolving b promise 
making a promise 
making b promise 
resolving b promise 
resolving a promise(2) 
done(2)

Which I find strange. Stranger still is when I set a break point and step through line for line, the output is what I would expect:

making a promise
making b promise
resolving b promise
resolving a promise
done
making a promise
making b promise
resolving b promise
resolving a promise
done

Why is this happening and how do I fix it?

I'm running an up to date Firefox 45.0.1. It also appears to be happening in Chrome.

Community
  • 1
  • 1
Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • 2
    Did you deliberately use the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)? – Bergi Apr 06 '16 at 23:38
  • 1
    What is so strange about the first output? Notice that `(2)` in the log just means that exactly the same message was logged twice. – Bergi Apr 06 '16 at 23:39
  • 2
    When you stop in the debugger, that allows asynchronous actions to complete. – Barmar Apr 06 '16 at 23:40
  • Apparently the debugger messes with the microscheduling queue. Which should be considered a bug imo. – Bergi Apr 06 '16 at 23:40
  • @Bergi. Semi deliberately. It was easier atm. – Seph Reed Apr 06 '16 at 23:42
  • @Barmar Nothing about these actions seems like it should be asynchronis. I was thinking that something with console might be what's happening, but I'm getting the same issue on a much larger scale in another project – Seph Reed Apr 06 '16 at 23:43
  • It is not a issue. It is working as expected. Promises are for deferred execution. When executing "aPromise().then(logDone)", it is returning a promise. The initial log what you get are during the process of returning the promise. – Ananthaprakash Apr 06 '16 at 23:51
  • 1
    @SephReed: No. *All* promise `then` callbacks are asynchronous. Always. Guaranteed. Even when the promise is already resolved. That's one of their big advantages - and an invariant the debugger is breaking here. – Bergi Apr 06 '16 at 23:52

0 Answers0