Promise rejected with error warning

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

Not quite sure why, I would like to help understand the error and cause it. Still learning Promises and AJAX, so very grateful! (For example, as I write this, I also think it is a little redundant to promise an ajax object, but to be honest, I don't know how to rewrite 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(); }) 

The UPDATE warning message is saved when I have .fail as:

 .fail(function(jqXHR, textStatus, errorThrown) { reject(new Error(errorThrown)) }) 
+5
source share
2 answers

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

 throw 42; 

This gives us a wonderful uncaught exception: 42 .

To throw the actual error, use Error :

 throw new Error('An actual error'); 

Now in your specific case, you need to pass the error that jQuery provides, which is not the first argument that it passes. It gives you a string, so wrap it in error ...

 .fail(function(jqXHR, textStatus, errorThrown ) { reject(new Error(errorThrown)); } 
+2
source

For example, when I write this, I also think that it is a little redundant to promise an ajax object, but to be honest, I don’t know how to rewrite it otherwise

You can define a function that returns the AJAX object that is specified in jQuery docs , returns an object that uses the Promise JavaScript interface.

The jqXHR objects returned by $ .ajax () with jQuery 1.5 implement the Promise interface, providing them with all the properties, methods, and behavior of Promise (see the “Deferred Object” section for more information).

Here is a sample code on how to implement such a function. I am using the Random User API like data.

 function getRandomUser() { return $.ajax({ url: 'https://randomuser.me/api/', dataType: 'json' }) .fail(error => console.error(error)); } // getRandomUser return value is a Promise like object, which we can chain onto getRandomUser() .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> 
0
source

Source: https://habr.com/ru/post/1273064/


All Articles