For example, you read your user settings from local storage (that’s a callback!). Based on those settings, you make a request from some external server with a database connection, (that’s callback #2). Before you render that information on the screen, you retrieve something else from the database (that’s callback #3).
These steps are very common when you build a large enterprise app. In your code, there will be a callback function, written in a callback function, that’s in another callback function. You can imagine if these functions are spread over separate files that you’d have a hard time reading this code back a month later.
A Promise typically has one of these 4 states.
- fulfilled – when the promise succeeds
- rejected – when the promise failed
- pending – ongoing, hasn’t been fulfilled or rejected yet
- settled – it has been fulfilled or rejected already
Here’s an example of a function that returns a Sencha Promise object:
Ext.Promise constructor takes one argument, a
callback with two parameters, resolve and reject. When it does
something asynchronous within the callback, like retrieving user
settings from a local storage store, then it calls “resolve”;
if everything worked it passes in the result, otherwise it calls “reject”
and passes in what went wrong.
Here’s how you use that Promise:
The “then” takes two arguments, a callback for a success case, and another one for the failure case our website. Both are optional, so you can add a callback for the success or failure case only. You can chain as many then methods as you want to run additional async actions one after another.
“then()” instance method, there are also
ways to terminate a Promise chain (
pending chains (
“cancel()”). Also, there’s a way to
attach an onCompleted callback to the chain (
for example with cleanup logic regardless the outcome. And, you can
attach an onRejected callback, if one action
within the chain is rejected (
example to handle failures.
In addition to
Ext.Promise, Sencha will also ship
Ext.Deferred, which is a mechanism used to create new
Promises within Ext JS 6. The difference between these two
constructors is that with a deferred constructor the creator has
direct access to “behind the scenes” extras, such as progress
Last but not least, Sencha integrated Promises support into
Ext.Ajax.request() is now an instance of a class
derived from Ext.data.request.Base which can be used with a then
method. It allows you to write code like this: