ES6 Promise and Class Conflict

I am very confused why sometimes, when I use a combination of a class instance with a promise, I get two kinds of errors. If I use Promise.all () with two or three chains of promises, I sometimes get only an undefined error in the callback. When I have a complex class with several properties and methods, I have an undefined instance of my class with my .then (). If my class is simple and I use only one or two chains of promises, I have no errors. Does anyone know why this could be? Here is an example of the code structure I'm aiming for:

(Code runs correctly in the latest Firefox Nightly, but not in Chrome 47)

'use strict'; class Controller { constructor() { this.data = 'data'; this.moredata = 'data'; this.evenmore = ['a', 'b', 'c']; this.dataobj = {"a" : "1", "b" : "2", "c" : "3"}; } } //BLOCKED CODE { let cc = new Controller(); let loadeddata = null; let xhr = $.getJSON('chapters.json', {}, (response) => { loadeddata = response; //SOMETIMES IF CLASS IS COMPLEX IS NOT DEFINED (SOMETIMES IT IS) }).fail(() => { console.log('Failed to load JSON data!'); }); let xhr2 = $.getJSON('chapters.json', {}, (response) => { loadeddata = response; }).fail(() => { console.log('Failed to load JSON data!'); }); let xhr3 = $.getJSON('chapters.json', {}, (response) => { loadeddata = response; }).fail(() => { console.log('Failed to load JSON data!'); }); let xhr4 = $.getJSON('chapters.json', {}, (response) => { loadeddata = response; }).fail(() => { console.log('Failed to load JSON data!'); }); //SOMETIMES WITH COMPLICATED CLASS WITH ONE OR TWO PROMISES DOES NOT THROW ERROR Promise.all([xhr, xhr2, xhr3, xhr4]).then(() => { console.log(loadeddata); console.log(cc); //SOMETIMES CC IS NOT DEFINED (SOMETIMES IT IS) }); } 
+5
source share
1 answer

jquery $.ajax does not return standard promises, so you should not use Promise.all with them (although you can), you can use $.when , not jquery. And instead of listening to failure or success on every deferred / promise, you can listen all the time with $.when

 var xhr1 = $.getJSON('chapters.json'); var xhr2 = $.getJSON('chapters.json'); var xhr3 = $.getJSON('chapters.json'); $.when(xhr1, xhr2, xhr1) .done(function(response1, response2, response3){ }) .fail(function(data, textStatus, jqXHR){ // first failed xhr }); 

(Code runs correctly in the latest Firefox Nightly, but not in Chrome 47)

the reason that it doesnโ€™t work in chrome 47 and works with Firefox Nightly is that the ES6 class es is not yet fully supported in chrome state (it is now under the flag of the chrome://flags/#enable-javascript-harmony function in chrome 47)

0
source

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


All Articles