Search code examples
javascriptes6-promise

JS Promise reject executes the then block and throws error


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();
        });
    });

}


Solution

  • 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))