Eugene Lurks
Eugene Lurks

Reputation: 111

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();

Upvotes: 0

Views: 86

Answers (2)

guest271314
guest271314

Reputation: 1

You can return foo() and bar() from the respective function, then pass foo and bar to .then() .then(foo).then(bar) or return foo() and bar() from .then(function(){ return foo() })

const p = Promise.resolve();

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

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

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

Upvotes: 0

Lokua
Lokua

Reputation: 576

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

Upvotes: 1

Related Questions