How Did I Start To Use Promises, Async, and Arrow Functions For Ajax Requests?

As we all know that we learn gradually. I was using ajax requests directly, it was working but my new way is more interesting and good for me. I am a mid-level developer, and I really enjoy when I use promises, async, and arrow functions for ajax requests.

From My Code Editor

So before knowing about promises, async, and arrow functions I was using ajax requests directly on click event. But later I changed my way, so the following would be my approach to use ajax for removing role from a user.

In the first step, I would make sure that I am sending the right data type values to the server, for that I would validate values

isNumeric = value => {
return new Promise((res, rej)=>{
if(typeof value === "number" && value !== 0 && Number.isNaN(value) === false){
res(value);
}else{
rej('Only numeric value allowed for this request.');
}
});
}

isNumeric() function validates values and returns an error message if it finds any non-numeric value.

In the next step, I would add a method for ajax request. In which I would use promise and this promise would help to return messages accordingly.

This arrow function would process ajax request with provided userId and roleId and based on server response it would return message in promise.

processAjaxRequest = (userId, roleId) => {
return new Promise((res,rej)=>{
$.ajax({
url:"server-url.php",
data:{
userId:userId,
roleId:roleId
},
type:'post',
dataType:'json',
success:response=>{
if(response.status==='success'){
res('Role successfully removed from user.');
}else{
rej('Role could not found for this user.');
}
}
});
});
}

Now we need one more, in which we would use the above two arrow functions. This would be an async arrow function.

unAssign() is an async function, in which trystatement would be true when all methods returns resolve() or on success event we can say. In case of failure, catch() statement would display an error message.

One more thing I am using toastr which displays message, you may append of display in any other way.

unAssign = async (userId, roleId) => {
try{
const validatedUserId = await isNumeric(userId);
const validatedRoleId = await isNumeric(roleId);
const result = await processAjaxRequest(validatedUserId,validatedRoleId);
toastr.success(result);
}catch(err){
toastr.error(err);
}
}

In the last we simple call unAssign() function on the on-click event.

$('#roles').on('click', '.delete-role', function(event){
event.preventDefault();
/* I removed script for getting dynamic ids just for here */
unAssign(userId,roleId);
});

So in this way, your ajax request would be complete with the proper response.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store