0

First of all, I would like to apologize for not being able to expose my original code here, due to the following reasons:

  1. It's too lengthy.
  2. It contains sensitive business information.

However, I believe the following outline should be enough to describe something weird happen to my promise chaining code (see the comments in code):

return new Promise((resolve, reject) => {

    return somePromiseFunction()
       .then(async allAccSummaries => {
          // Some very lengthy codes here.
          // Contains several await function calls.
    
          let batchResult = { 
             // Some property assignments here 
          };
          console.log(batchResult); // Confirmed batchResult is NOT undefined.
          return resolve(batchResult); // This was the result returned to the caller instead!
       })
       .then(prevBatchResult => {
          console.log(prevBatchResult); // prevBatchResult is undefined, why?
    
          // Some other very lengthy logics here.
    
          let finalBatchResult = { 
             // Some property assignments here 
          };
          return finalBatchResult; // This was not returned to caller as final result!
    
       }

}

I wonder how can this be possibly happened? I know that the only reason for the then() parameter to be undefined is when the previous then() was not returning anything, but this isn't true for my case. Also, I want the result of the final then() to be returned to the caller, not the first one. Can somebody point out to me any possibility that can cause this to happen? Thanks in advance!

Antonio Ooi
  • 1,601
  • 1
  • 18
  • 32
  • 1
    OK, I'm not sure if this is directly related to your issue but it's the first thing I noticed in your code: [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/q/23803743) – VLAZ Feb 25 '21 at 09:37

1 Answers1

1
console.log(prevBatchResult); // prevBatchResult is undefined, why?

Because the return value of the previous then() function is return resolve(batchResult); and the resolve(...) function returns undefined.

Your problem is caused by the explicit-construction anti-pattern.

  • Remove return new Promise((resolve, reject) => { (and the matching });.
  • Don't call resolve just return the value (batchResult) you want to resolve the promise with.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335