Ayush
Ayush

Reputation: 709

Using a function that returns a promise, inside a then() block

I have a promise chain as follows :

return performTaskA().
then(performTaskB).
then(performTaskC).
then(performTaskD).
then(performTaskE);

performTaskD is as follows :

function performTaskD() {
    Model.something().
    then(function(result) { 
         something something with result; //BREAKPOINT 1
    }); 
}

When I run the promise chain above, BREAKPOINT 1 never gets hit and the control proceeds to performTaskE. However, when I call the function performTaskD() separately, BREAKPOINT 1 does get hit. What am I doing wrong in the case of the promise chain?

If I return the promise in performTaskD, I still have the same issue. The only difference is that the control never proceeds to performTaskE and the process exits.

For clarity, performTaskD is as follows :

AccountModel.findById(acctId).
    then(function (account) {
        destAccount = account; //destAccount is a var declared in the outer scope.
});

Upvotes: 0

Views: 2463

Answers (3)

Anmol Mittal
Anmol Mittal

Reputation: 853

"then" function is called when a promise is resolved. In your task functions, you handle the promise inside the function itself, so the rest of the chain's "then" doesnt gets called.

Use Promise.resolve

function performTaskD() {
   return Model.something().
   then(function(result) {             
        something something with result; //BREAKPOINT 1
        Promise.resolve(result)
   }); 
}

Upvotes: 0

Lucas
Lucas

Reputation: 4097

According to Mongoose documentation Model.find(something) does not return a promise. You need to call Model.find(something).exec(). The performTaskD should be something like:

function performTaskD(AcctId) {
  return AccountModel.findById(AcctId).exec().
  then(function (account) {
    destAccount = account;
    return account;
  });
}

Upvotes: 0

guest271314
guest271314

Reputation: 1

return the Promises

function performTaskD() {
    return Model.something().
    then(function(result) { 
         return something something with result; //BREAKPOINT 1
    }); 
}

Upvotes: 3

Related Questions