Yash Bagadia
Yash Bagadia

Reputation: 41

resolving a Promise inside failure of another promise

I want to resolve a promise which in turn makes an ajax call. The promise should be resolved irrespective of the fact whether the ajax call was successful or not. I tried the following snippet:

new Promise(function(resolve, reject) {
  $.ajax({
    url: "nonExistentURL",
    headers: {
      "Content-Language": "en"
    },
    async: true,
    type: "DELETE",
    contentType: "application/json",
    crossDomain: true,
    dataType: "json"
  }).done(function(oSuccessData) {
    debugger;
    resolve(oSuccessData);
  }).fail(function(oData) {
    debugger;
    resolve(oData);
  });
}).then(function(oData) {
  debugger;
}).catch(function(err) {
  debugger;
});

But, this seems to be entering the catch callback always. Why it is not entering the then callback?

Upvotes: 4

Views: 102

Answers (1)

Sivasankar
Sivasankar

Reputation: 803

It is actually because of the argument that you are receiving in fail callback. It is an XHR then-able promise type object. Since you are resolving the function with a rejected promise, it comes to the catch block.

You could just wrap the error object in another object say { err: oData }, then the then callback will get resolved properly.

new Promise(function(resolve, reject) {
    $.ajax({
        url: "nonExistentURL",
        headers: {
            "Content-Language": "en"
        },
        async: true,
        type: "DELETE",
        contentType: "application/json",
        crossDomain: true,
        dataType: "json"
    }).done(function(oSuccessData) {
        console.log("Done callback: Resolving the promise with Data");
        resolve(oSuccessData);
    }).fail(function(oErr) {
        console.log("Fail callback: Resolving the error");
        resolve({ err: oErr });
    });
}
).then(function(oData) {
   console.log("Then Callback");
}).catch(function(err) {
   console.log("Catch the error");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 5

Related Questions