Eugene Lurks Eugene Lurks - 3 years ago 328
Javascript Question

Chain promise using functions doesn't return desired callback sequence

1.I'm trying to chain some promises with using functions on a global promise object. The chain sequence doesn't work as I thought. The following code output 1 3 4 2.
2.I wonder what is the reason for this. My thought is in the variable declaration pass, p.then() function registered but not its following promises, not until the p.then() function returns, it start to push the second then function in callback queue.

To answer the question why I'm doing this, I was trying to use an builder pattern for a sequence of actions.
For example, builder().setupTestEnv().connectToDatabase().setupAuthServer().setupAuthClient(). Each function in this chain is intended to do _globalPromiseObject.then() to chain up following actions.

I know an alternative solution for this is, end the builder chain with an execute() call, which run Q.all() to run all promises in sequence. But just curious about this behavior of promise chain.

const Q = require('q');

const p = Q();

p
.then(
function(){
console.log(1);
}
)
.then(
function(){
console.log(2);
}
);

function foo(){
p.then(
function () {
console.log(3);
}
);
}

function bar(){
p.then(
function () {
console.log(4);
}
);
}

foo();
bar();

Answer Source

Not sure if this 100% answers your question, but perhaps it is helpful to look at this in terms of meaningful statements in your example:

  1. p.then()
  2. foo()
  3. bar()
  4. finally, #1's then fires

Those three operations happen immediately after each other, synchronously. Let's remove the foo and bar wrappers, as if you wrote their contents in place of calling them:

  1. p.then(/* log 1 */)
  2. p.then(/* log 3 */) contents of foo
  3. p.then(/* log 4 */) contents of bar
  4. finally, #1's then fires
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download