Reputation: 1983
Account.findByOwnerID(userID)
.then(function(account) {
return validateTo(account, userID);
})
.then(User.findByUsername(email))
In this case, findByOwnerID runs, but as soon as the Promise.all() inside of it starts running, findByUsername starts being executed, skipping over validateTo.
A simple change in the code makes it all work how I'd expect.
Account.findByOwnerID(userID)
.then(function(account) {
return validateTo(account, userID);
})
.then(function() {
return User.findByUsername(email);
})
Using this code, findByOwnerID runs, then when it resolves, validateTo runs. When that resolves, findByUsername is ran.
So why does this work and not the one above? The way I understood promise chaining was that each .then() expected to be given a promise, which when resolved, will trigger the next .then().
Some background on the functions used (I can give more details in these if needed)
Account.findByOwnerID and User.findByUsername are functions that return a promise. Inside of that promise they use Promise.all.then(function() {resolve()}, to return the main promise and continue the chain.
validateTo is a function that returns a promise.
Upvotes: 5
Views: 1498
Reputation: 239260
This has nothing to do with promises. It's simple function invocation.
You're effectively asking why a(b())
behaves differently than a(function () { b() })
. The simple answer is that in the first, b()
is executed and then the result is passed to a()
, while in the second, a()
executes and is passed a function that may or may not be invoked at some point in the future.
.then(b())
invokes b
immediately, and the return value (whatever that may be) is passed into then
. This is what your first case does.
.then(function () { b() })
passes a function into then
. It's up to then
to decide when/if to execute that function. This is what your second case does.
Upvotes: 11