0

I am trying to create a Javascript promise for a ajax call. If it returns the right response, I am resolving it and had attached the corresponsing then block to the Promise. If it rejects, I have a catch block for that. Unfortunately, for me, eventhough i reject, the then block in the promise gets executed. Please help me address this. Below is the code block I am using in my app.

function check (){   
return new Promise ((resolve, reject) => {
        $.ajax({
        type:"get",
        url : "API",
        data:{"jsonData":"validJsonData"},
        async:true,
        success:function(responseMap){
            if(responseMap.data && JSON.parse(responseMap.data)) {
                resolve(responseMap)
            }else{
                reject(responseMap.message)
            }
        },error : function(errorObj){
            reject(errorObj)
        }
    }).then(result => {
            let obj= JSON.parse(result.data);
            // process obj
            loader.hide();
        }).catch(error => {
            console.log(error)
            // error handle logic
            loader.hide();
        });
    });

}

Mahesh
  • 7
  • 5
  • 3
    What is your error? Some 'errors' are perfectly valid responses from a server and wouldn't bee interpreted as an error and therefor wouldn't `catch`. It's probably the `asyncServerResponseValid ` thats not what you expect it to be. Also, try fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – somethinghere Sep 14 '20 at 05:04
  • 1
    The promise shown really doesn't make sense since nothing shown is asynchronous. Where does `asyncServerResponseValid` come from and what is it? – charlietfl Sep 14 '20 at 05:08
  • 1
    @somethinghere first of all, thank you for your comments. As you pointed out, In my case error is a valid response from API. Unfortunately, I had set the status code of response to 200 for the error message. Now I changed it to 404, which the jquery considers as error and rejects. Thank you very much for pointing me to the right direction. Also, Thank you for suggesting fetch API. This has many benefits in my case over the usage of jquery ajax calls. I am going to refactor to the same. – Mahesh Sep 14 '20 at 05:21
  • @charlietfl thank you for your comments. Sorry. It's my bad, I removed the jquery ajax call block from the promise. I will edit the question. – Mahesh Sep 14 '20 at 05:23
  • 3
    It's an anti-pattern to wrap `$.ajax()` in a promise because it ALREADY returns a promise that you can just use. You can already do `$.ajax(...).then(...)`. – jfriend00 Sep 14 '20 at 05:29
  • 1
    I still don't understand why the final approved answer here still uses jQuery when there is a native fetch API in the browser. Apart from familiarity or legacy, there should be no reason no use jQuery anymore, yet everyone just keeps pointing at it. Anyhow, nice to know your problem got resolved! – somethinghere Sep 14 '20 at 13:50
  • 1
    @somethinghere To be frank, I am only aware of fetch API after this post, thanks to you. Unfortunately, the app I am dealing with falls in legacy category, in which I am developing a new feature. However, after this, I had pitched the idea of fetch in our team. Thank you for your helpful comments sir. – Mahesh Sep 15 '20 at 14:24

1 Answers1

1

You are using the explicit promise construction antipattern since $.ajax already returns a Promise.

Also the success callback of $.ajax is not part of it's promise chain so use then() instead

Your code should look more like:

function check() {  
    // return the $.ajax promise  
  return $.getJSON(url, { "jsonData": "validJsonData" }).then(function(responseMap) {
    // not sure why you had extra JSON.parse() in here
    if (responseMap.data) {
      return responseMap.data
    } else {
      return Promise.reject(responseMap.message)
    }    
  }).then(function(result) {    
    loader.hide();
    // return to next then()
    return result
  }).catch(error => {
    console.log(error)
    // error handle logic
    loader.hide();
  });    
}

// usage
check().then(data=>console.log(data))
charlietfl
  • 170,828
  • 13
  • 121
  • 150