bendrucker / ama

Ask me questions about building web applications
MIT License
6 stars 1 forks source link

Using promise.finally #17

Closed bsiddiqui closed 9 years ago

bsiddiqui commented 9 years ago

I've been trying to get a better understanding of when to use Bluebird's .finally. Since it's called regardless of the promise's fate, it sounds like

return somePromise()
.finally(doSomething)

is doing something similar to

return somePromise()
.then(doSomething, doSomething)

I've had a couple situations where they haven't reacted in the same way so when would you use .finally?

bendrucker commented 9 years ago

1 is definitely not equivalent to 2. Finally is there for when you want to do something regardless of outcome. There is no input to doSomething whereas in case 2 you're shoving two random inputs in there which won't go well.

function load () {
  loading.set(true)
  return getData()
    .then(data.set)
    .catch(error.set)
    .finally(function () {
      loading.set(false)
    })
}

loading.set(false) should always be evaluated when we're all done, regardless of the outcome. And its evaluation should happen after a promise resolves, but doesn't depend on the fulfillment value of getData