Aura中调用服务器端方法的通用方法

// In helper
callServerAction : function(component, action) {
	return new Promise(function(resolve, reject) {
		action.setCallback(this, function(response) {
			let _state = response.getState();
                	if (_state === "SUCCESS") {
                    		resolve(response.getReturnValue());
                	} else {
                    		let errors = response.getError();
                    		let message = "Error";
                    		if (errors && Array.isArray(errors) && errors.length > 0) {
                        		message = errors[0].message;
                    		}
                		reject(new Error(message));
                	}
            	});
            	$A.enqueueAction(action);
	});
},

// In Controller
doMethod : function(component, event, helper) {
        let myAction = component.get("c.doSomething");
        myAction.setParams({
            "param1": param1
        });
        let myAcitonPromise = helper.callServerAction(component, myAction);
        myAcitonPromise.then(function(_returnValue) {
             // DO SOMETHINT OR CONTINUE PROMISE
	}).catch(function(_error) {
    		console.error(_error);
	}).finally(function() {
	});

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据