1

I wrote this piece of code where I get the Json from an ajax call. I need to handle the response (success, error) with javascript promise (resolved after 2 seconds) and .then() method. I read a few stuff online but don't know where to begin. Can anybody help me please? Thanks

function jsonResult(spaceName){
   var baseUrl = "BaseUrl";

    $.ajax({
      url:baseUrl + "/api/request/url",
      type:"GET",
      dataType: "json",
      error: function(xhr,status,error) {
          console.log(JSON.stringify(error));
      },
      success: function(response){
         getResult(response)
     }
  });
}
J.D.
  • 29
  • 4

3 Answers3

0

You just need to update your function to return a promise and then in your success and error methods just call resolve and reject respectively. Here is a sample pulled from MDN:

function myAsyncFunction(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
}

You can read more on this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Here is a simple implementation of your example code:

function jsonResult(spaceName){
   var baseUrl = "BaseUrl";

   return new Promise((resolve, reject) => {
    $.ajax({
          url:baseUrl + "/api/request/url",
          type:"GET",
          dataType: "json",
          error: function(xhr,status,error) {
              reject(JSON.stringify(error));
          },
          success: function(response){
             resolve(response);
         }
      });
  });
}
Adam H
  • 1,750
  • 1
  • 9
  • 24
0

You can user return a promise on calling this function which will resolve in success callbacka and will be rejected in error callback like this

function jsonResult(spaceName){
   var baseUrl = "BaseUrl";
    return new Promise((resolve, reject) => {
      $.ajax({
        url:baseUrl + "/api/request/url",
        type:"GET",
        dataType: "json",
        error: function(xhr,status,error) {
            console.log(JSON.stringify(error));
            reject(error);
        },
        success: function(response){
           resolve(getResult(response));
       }
      });
   }
}

// Usage

jsonResult(someInput).then(response => {
  // success
})
.catch(error => {
  // error
});
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

jQuery 3.0 is Promises/A+ compatible so just remove the error/success and do the then/catch

function jsonResult(spaceName) {
  var baseUrl = "BaseUrl";

  $.ajax({
    url:baseUrl + "/api/request/url",
    type:"GET",
    dataType: "json"
  }).then(console.log, console.error)
}

alternativ is the the native fetch api...

fetch(baseUrl + "/api/request/url")
  .then(res => res.json())
  .then(console.log)
Endless
  • 34,080
  • 13
  • 108
  • 131