我很困惑为什么有时当我使用类的实例和promise的组合时,我会得到两种错误。如果我使用带有两个或三个链式承诺的 Promise.all(),我有时只会在回调中得到一个未定义变量的错误。当我有一个包含多个属性和方法的复杂类时,我的 .then()我的类的未定义实例如果我的类很简单,我只使用一个或两个链式承诺我没有错误。有没有人知道为什么会这样?以下是我的目标代码结构示例:
(代码在最新的Firefox Nightly中正确执行,但不在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)
});
}
答案 0 :(得分:0)
jquery $.ajax
没有返回标准的承诺,因此您不应该使用Promise.all
(尽管可以),您可以使用$.when
代替jquery等效。而不是在每个deferred / promise上听取失败或成功,您可以使用$.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
});
(代码在最新的Firefox Nightly中正确执行,但不在Chrome 47中执行)
它在chrome 47中不起作用并且正在使用Firefox Nightly的原因是,Chrome中还没有完全支持ES6 class
es(它在chrome 47中的功能标记当前为chrome://flags/#enable-javascript-harmony
)