I recently started working with Angular and found myself in a large project. I encountered a simplified version of my code below:
var beforeClose = function() {
var closeDeferred = $q.defer(),
a = $q.defer(),
b = $q.defer(),
c = $q.defer(),
promiseArray = [a.promise, b.promise, c.promise];
/* logic that resolves or rejects a, b, and c */
$q.all(promiseArray).then(
function() {
closeDeferred.resolve();
},
function() {
closeDeferred.reject();
}
);
return closeDeferred.promise;
}
var modalClose = function() {
beforeClose().then(
function() {
//close the modal
},
function() {
//warn and don't close modal
}
)
}
While using Chrome's DevTools, I noticed that the code is returning closeDeferred
promise before promiseArray
is fully resolved or rejected. So my question is,
When is the promise returned? Can it be returned before being resolved or rejected? If not, how can I prevent it from being returned prematurely?
Moving the return statement into a separate function (e.g., within the resolve and reject functions of promiseArray
) does make that function return the promise, but it doesn't necessarily pass that promise to modalClose
(which initiated the first promise).
Or perhaps I am misunderstanding the behavior of my code. When I placed the closeDeferred
return into another function, I received errors indicating that .then()
cannot be called on undefined (pointing at the beforeClose().then()
line).
Edit: After reviewing Andrew's answer, I made updates to the code and need to clarify what's happening.
The issue is not necessarily that the promise is returned sooner than desired, but rather that it executes the resolve function for that promise -- closing the modal even though promiseArray()
hasn't finished processing.
Edit 2: It appears that by simplifying the code structure, I inadvertently removed the actual problem. In setting up the promises differently, I neglected to define closeDeferred as a defer or a promise before the return statement. As a result, when the loop executed its task, it also returned closeDeferred.promise as undefined, causing the modalClose function to run before any promises were resolved/rejected. Only in the subsequent loop was closeDeferred finally defined and the promises behaved correctly.
I still greatly appreciate the assistance provided. @andrew-tomlinson and @georgeawg both enhanced my understanding of promises significantly. While it did not directly solve this specific issue (due to my misidentification), the guidance offered was incredibly valuable. Thank you!