JavaScript Promise then() ordering

The reason you see 6 early is because you didn't chain, you branched.

When you call p.then().then().then(), you've got a chain of promises that must execute in the correct order.
However, if you call p.then().then(); p.then(), you've got 2 promises attached to p - essentially creating a branch, and the 2nd branch will execute along with the first.

You can fix this by ensuring you chain them together p = p.then().then(); p.then();

FYI, you almost NEVER want to branch, unless you bring them back together (eg. Promise.all), or are intentionally creating a "fire and forget" branch.


What does r() do?

The ordering is indeterminate because you're thenning on the same promise -> this specifically refers to the second and third chain.

If you were doing the following, then order can be guaranteed:

var p = Promise.resolve().then(function() {
    w(0);
}).then(function() {
    w(1);
});

// Key difference, continuing the promise chain "correctly".
p = p.then(function() {
    w(2);
    return new Promise(function(r) {
        w(3);
        r();
    }).then(function() {
        w(4);
    });
}).then(function() {
  w(5);
});

p.then(function() {
  w(6);
});