Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise rejected with non-error warning

Error: h1.js:25 Warning: a promise was rejected with a non-error: [object String]

Not entirely sure why, would love help understanding the error and what's causing it. Still learning Promises and AJAX so help greatly appreciated! (For example, as I write this I also think it's a bit redundant to have a Promise wrapping an ajax object, but honestly I don't know how to re-write it otherwise)

var logisticsModule = (function() {
  return {
    initialize: function() {
      dateTimeFxns.getReservedDates.then(
        // success
        function(reserved_dates) {
          console.log("success with value = " + reserved_dates)
        },
        function(error) {
          console.log("error with value = " + error)
        }
      )
    }
  }
})();

var dateTimeFxns = {
  getReservedDates: new Promise( function(resolve, reject) {
    $.ajax({ 
      // some url & data
    })
    .done(function(result) {
      resolve(result)
    }
    .fail(function(error) {
      reject(error)
    }
  })
}

$(document).ready(function() {
  logisticsModule.initialize();
})

UPDATE warning message persists when I have the .fail as:

.fail(function(jqXHR, textStatus, errorThrown) {
  reject(new Error(errorThrown))
})
like image 969
james Avatar asked Nov 01 '17 20:11

james


1 Answers

This just means that the error that was thrown is not an instanceof Error. For example, the following is not an error, but I can throw it because... well... you can throw anything in JavaScript.

throw 42;

Which gives us a wonderful uncaught exception: 42.

To throw an actual error, use an Error:

throw new Error('An actual error');

Now in your specific case, you need to pass the error that jQuery supplies, which isn't the first argument it passes. It gives you a string, so wrap it in an error...

.fail(function(jqXHR, textStatus, errorThrown ) {
  reject(new Error(errorThrown));
}
like image 64
Fenton Avatar answered Sep 19 '22 21:09

Fenton