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)
The . promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended. By default, type is "fx" , which means the returned Promise is resolved when all animations of the selected elements have completed.
The Deferred object can be employed when performing asynchronous operations, such as Ajax requests and animations. In jQuery, the Promise object is created from a Deferred object or a jQuery object. It possesses a subset of the methods of the Deferred object: always() , done() , fail() , state() , and then() .
version added: 1.5deferred. The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With