Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Promises In Lightning
{
doInit : function(component, event , helper){
var action = cmp.get("c.getCurrentUser");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.user", response.getReturnValue());
}
else {
alert('error');
}
})
}
}
{
doInit : function(component, event , helper){
var action = cmp.get("c.getCurrentUser");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.user", response.getReturnValue());
}
else {
alert('error');
}
action = cmp.get("c.getCases");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.cases", response.getReturnValue());
}
else {
alert('error');
}
});
})
}
}
public class LightningCtrl {
@AuraEnabled
public static User getCurrentUser(){
return [
SELECT Id, Name, ContactId, AccountId
FROM User
WHERE Id =:UserInfo.getId()
];
}
@AuraEnabled
public static List<Case> getCases(){
return [
SELECT Id, CaseNumber, Subject
FROM Case
WHERE OwnerId =:UserInfo.getId()
];
}
}
{
doInit : function(component, event , helper){
helper.call(component.get("c.getCurrentUser")).then(function(user){
// called when the method was successful
component.set("v.user", user);
}).catch(function(err) {
alert('error')
})
},
}
{
doInit : function(component, event , helper){
helper.call(component.get("c.getCurrentUser")).then(function(user){
// called when the method was successful
component.set("v.user", user);
},function(err){
// error handler
alert('error');
})
}
}
{
doInit : function(component, event , helper){
helper.call(component.get("c.getCurrentUser")).then(function(user){
// called when the method was successful
component.set("v.user", user);
return component.call(component.get("c.getCases"))
}).then(function(cases){
component.set("v.cases", cases);
}).catch(function(err) {
alert('error')
})
}
}
{
call: function(action, params) {
return new Promise($A.getCallback(function(resolve, reject) {
if (params) {
action.setParams(params);
}
action.setCallback(this, function(a) {
var err = a.getError();
var result = a.getReturnValue();
if (err && err.length > 0) reject(err);
else resolve(result);
});
$A.enqueueAction(action, false);
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment