Skip to content

How to write AJAX function in promise

Last updated on December 17, 2023

Quick preview

  1. Overview
  2. Write as normal way
  3. Write in a Promise
  4. Conclusion

1. Overview

2. Write as normal way

// Normal way
function callAjax(url, type, data, cbOk, cb_bfsend, _cbNo) {
  $.ajax({
    url  : url,
    type : type,
    data : data,
    beforeSend: function () {
      if(cb_bfsend != undefined) cb_bfsend();
    },
    success: function(data, type) {
    /**
     * Success method is used on Ajax call successfully
     * Do not handle backend error on this method.
     */
      if(cbOk!= undefined) {
        cbOk(data);
      }
    },
    error: function(data) {
      if (_cbNo!= undefined) _cbNo();
    }
  });
}

// Usage
function anotherFunc() {
   // Do something
   callAjax(
      "https://api.com",
      "POST",
      {
         id: 1234
      }, 
      function() {
         alert("I am successful to call AJAX");
      },
      function() {
         alert("AJAX is loading");
      },
      function() {
         alert("I failed to call AJAX");   
      }
   );
}

3. Write in a Promise

// Inside promise
const callAjax = (url, type, data) => {
  return new Promise((resolve, reject) => {
    $.ajax({
      type,
      url,
      data: JSON.stringify(data),
      datatype: 'json',
      success: function(response){
        resolve(JSON.parse(response));
      },
      error: function(err) {
        reject(err);
      },
      fail: function(err) {
        reject(err);
      }
    });
  });
}

// Usage
async function anotherFunc() {
   let result = await callAjax(
      "https://api.com",
      "POST"
      {
         id: 1234
      },
   );

   if(result.code === 200) {
     alert("I am successful to call AJAX");
   } else {
     alert("I failed to call AJAX");
   }
}

4. Conclusion

NormalIn promise
– Too long and many parameters to input
– Many callback function that is hard to debug
– Because of callback function so, we are struggling to pass variables into result handler.
– Async progress.
– Shorter
– No callback function needed.
– Functions are sequent to run in process.
– Easy to catch result and do handlers after
– Sync progress.
Published in⌨️ Programming TipsBlogs

Comments are closed.