Skip to content
Advertisement

Why are Javascript promises resolving out of order?

I am attempting to use JavaScript promises in a project and the order of events are unexpected. I have narrowed it down into a small demo using a test promise.

JavaScript

And then I call it like so:

JavaScript

This is the console output:

JavaScript

How can I get an output of:

JavaScript

Advertisement

Answer

.then() expects a function reference. When you do something like this:

JavaScript

you are executing the function testPromise() immediately and passing the return value to .then(). This is almost never what you want (unless testPromises() returned another function) because for .then() to do its job, you MUST pass it a function reference (a function that it can call sometime later). If you execute the function immediately, then .then() can’t do its job and call it LATER.

Instead, what you want is this:

JavaScript

Or, you could use .bind():

JavaScript

So, your whole chain would look like this:

JavaScript

Or, using .bind()

JavaScript

If you’re doing this a lot, you could make a curry wrapper for testPromises() that would return another function. This is essentially what .bind() above was doing, but the syntax is a little prettier to use once you’ve declared your wrapper function.

JavaScript

Then, because that wrapper returns another function, you could then do:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement