I'm digging into jQuery's deferred features. I've tried several examples on the internet. I understood its concept, but I don't understand the difference between resolve()
and promise()
.
What are differences between resolve()
and promise()
?
Promise.reject(reason) Returns a new Promise object that is rejected with the given reason. Promise.resolve(value) Returns a new Promise object that is resolved with the given value.
Promise. resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned.
resolve("aaa") is the same as return Promise. resolve(Promise. resolve("aaa")) - since resolve is idempotent calling it on a value more than once has the same result.
The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.
Both resolve()
and promise()
are methods on the jQuery Deferred
object.
First a snippet from the jQuery documentation about Deferred:
One model for understanding Deferred is to think of it as a chain-aware function wrapper. The deferred.then(), deferred.done(), and deferred.fail() methods specify the functions to be called and the deferred.resolve(args) or deferred.reject(args) methods “call” the functions with the arguments you supply.
With that in mind, promise()
returns an object that is very similar to the Deferred
object except that it only has then()
, done()
, and fail()
methods and does not have resolve()
or reject()
.
From the blog post m-sharp referred to regarding promise()
:
This is useful when you want to give to the calling API something to subscribe to, but not the ability to resolve or reject the deferred.
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