27

I have something like the following:

getUser("foo").then(handleSuccess, handleError).always(tidyUp);

getUser returns a jQuery Deferred object.

I understand from this article that I can convert the Deferred object to a native Promise using Promise.resolve, so I can write

Promise.resolve(getUser("foo"))
  .then(handleSuccess)
  .catch(handleError)

The Promise API doesn't offer an always method though, so I'm wondering how that should be handled.

Is it as follows?

 Promise.resolve(getUser("foo"))
  .then(handleSuccess)
  .then(tidyUp)
  .catch(handleError)
  .then(tidyUp)
user5325596
  • 2,310
  • 4
  • 25
  • 42

2 Answers2

19

I think the following is what you're looking for:

 Promise.resolve(getUser("foo"))
  .then(handleSuccess, handleError)
  .then(tidyUp)

tidyUp will be always called. See the following jsbin for the full example: http://jsbin.com/lujubu/edit?html,js,console,output

Oleksii Rudenko
  • 1,277
  • 12
  • 23
  • 5
    Yes, that would work thanks. You also made me realise that I can also just do `Promise.resolve(getUser("foo")).then(handleSuccess).catch(handleError).then(tidyUp)`, i.e. keeping the `catch`. – user5325596 Oct 01 '15 at 10:30
3

Use your always function as the handler for resolve and reject to ensure it will always be called.

function getUser(result) {
    switch (result) {
        case 'good':
            return Promise.resolve();

        case 'bad':
            return Promise.reject();

        case 'ugly':
            return new Promise(() => { throw new Error() })
    }
}

function handleSuccess() { console.log('success') }
function handleError() { console.log('error') }
function tidyUp() { console.log('all tidy now') }


Promise.resolve(getUser('good'))
    .then(handleSuccess)
    .catch(handleError)
    .then(tidyUp, tidyUp);

Promise.resolve(getUser('bad'))
    .then(handleSuccess)
    .catch(handleError)
    .then(tidyUp, tidyUp);

Promise.resolve(getUser('ugly'))
    .then(handleSuccess)
    .catch(handleError)
    .then(tidyUp, tidyUp);

// success
// error
// error
// all tidy now
// all tidy now
// all tidy now

Promise API Reference

reergymerej
  • 2,371
  • 2
  • 26
  • 32