Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise chain executing out of order

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.

like image 533
Elliot Avatar asked Mar 28 '16 16:03

Elliot


1 Answers

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.

like image 167
meagar Avatar answered Sep 29 '22 14:09

meagar