2

I have angular 1.6 ES6 code that does this

service.get()
.then((data) => {
    console.log('one')
    //arbitrary stuff
    return service.get()
})
.then((data) => {
    console.log('two')
    //more stuff
})
.catch((err) => {
    //handle err
})
.finally(console.log('finally'))

and I want to get this from the console:

one
two
finally

but what I actually get is:

finally
one
two

How do I get this turned around so my finally doesn't happen until after my promise chain is complete?

Derek Chadwell
  • 696
  • 1
  • 8
  • 22

2 Answers2

5

Because you're calling console.log('finally') inmediately,

Replace:

.finally(console.log('finally'))

with:

.finally(() => console.log('finally'))

EDIT

From the docs:

Promise.prototype.finally takes a callback as a parameter, which when the promise is settled, whether fulfilled or rejected, the specified callback function is executed.

Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
  • You called it. I didn't think I needed to () => in these chains because they wouldn't get called until it was their turn. Can you explain or point me toward something that explains the difference between those cases? It's not altogether clear to me. – Derek Chadwell Feb 05 '18 at 22:44
  • 2
    @DerekChadwell You have to remember that `.finally()` is a function, not a language construct. So what you put between those `()` is evaluated immediately as an argument. Your original code had a function call in there, so the function call is evaluated as an argument to the `.finally()` function. Daniel's correct answer passes an arrow function (anonymous function) instead as a callback, which does not get executed until the promise engine determines it should. – JC Ford Feb 05 '18 at 22:52
1

Finally clause should receive callback function. In your code you are invoking function, not passing it: console.log('finally') invokes function immediately.

Possible solution would be to use anonymous function:

finally(() => {
    console.log("finally");
});

Or even shorter:

finally(() => console.log("finally"));
pwolaq
  • 6,343
  • 19
  • 45