Promise rejected with non-error warning
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));}
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
You could define a function that returns the AJAX object, which stated in the jQuery docs, returns an object that uses the JavaScript Promise interface.
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).
Here is a code example of how to implement such a function. I am using the Random User API for example data.
function getRandomUser() { return $.ajax({ url: 'https://randomuser.me/api/', dataType: 'json' }) .fail(error => console.error(error));}// getRandomUser's return value is a Promise like object, which we can chain ontogetRandomUser().then( function(random_user) { console.log("success with value = ", random_user) }, function(error) { console.log("error with value = ", error) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>