Search code examples
javascriptpromisees6-promisechainingmethod-chaining

Promises chaining, wrong order


I'd like to understand the promises chaining in Javascript. So I wrote this little fiddle: https://jsfiddle.net/GarfieldKlon/89syq4fh/

It works like intended. c waits for b, and b waits for a.

But when I change these lines to:

a().then( result => console.log(result))
.then( () => {b().then( result => console.log(result))})
.then( () => {c().then( result => console.log(result))});

So I added the curly braces around b and c and then the output is 1, 3, 2. And I don't understand why.

When I add a return then it works again:

a().then( result => console.log(result))
.then( () => {return b().then( result => console.log(result))})
.then( () => {return c().then( result => console.log(result))});

But why? When there are no curly braces you're only allowed to write one statement, correct? And this statement is implicitly returned?

And when you use curly braces you have to explicitly return something?

But why does it mess up the order when using curly braces without return? And why does it still log something when the return is missing?


Solution

  • When using the arrow syntax, you can interpret it in many things:

    () => 'hello'
    

    is equivalent to

    () => { return 'hello'; }
    

    However, when doing

    () => {'hello'}
    

    as similar to what you wrote:

    .then( () => {b().then( result => console.log(result))})
    

    then you can interpret that as

    () => {'hello'; return;}
    

    So, in the code, yours promise handling b().then( result => console.log(result)) is called before a void return; is done. You are not returning the resulting promise object at all. It gets called when b is finished, no matter of what you were doing.