Promise support in Lightning Components

Promises are supported in Lightning Components; however, care must be taken, in order to not use them when the action is marked as storable; the callback function should be wrapped in $A.getCallback(). (This is because Promises are asynchronous functions. Any asynchronous function, if used in the Lightning component framework, is wrapped in $A.getCallback(), to ensure that the framework re-renders the modified component and processes any queued actions.)

The following snippet shows the generic pattern to follow when using Promises. Note that the following code assumes that the snippet is part of the helper file:

({

getAccounts : function(component,event){
var fetchaccountAction = component.get("c.getAccounts");
var params={};
fetchaccountAction.setParams(params);
this.promiseAction(fetchaccountAction)
.then(
$A.getCallback(function(result){
// Set attributes

}),
$A.getCallback(function(error){
// Handle any errors
})
);
},

promiseAction : function(action){
return new Promise(function(resolve, reject) {
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var response = response.getReturnValue();
resolve(response);
}
else if (state === "ERROR") {

}
else {
reject(Error("Unknown error"));
}
}
});
$A.enqueueAction(action);
}

})

You can chain the Promises by using the following pattern:

firstPromise()
.then(
// resolve handler
$A.getCallback(function(result) {
return secondPromise();
}),

// reject handler
$A.getCallback(function(error) {
console.log("Promise was rejected: ", error);
return errorRecoveryPromise();
})
)
.then(
// resolve handler
$A.getCallback(function() {
return thirdPromise();
})
);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.20