我很困惑为什么有时当我将类的实例与 promise 结合使用时会出现两种错误。如果我将 Promise.all() 与两个或三个链接的 promise 一起使用,我有时只会在回调中收到 undefined variable 的错误。当我有一个具有多个属性和方法的复杂类时,我有一个未定义的类实例和我的 .then() 如果我的类很简单并且我只使用一个或两个链式 promise 我没有错误。有谁知道为什么会这样?这是我的目标代码结构示例:
(代码在最新的 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)
});
}
最佳答案
jquery $.ajax
不返回标准 promise,所以你不应该对它们使用 Promise.all
(尽管你可以),你可以使用 $ .when
而不是 jquery 等价物。您可以使用 $.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
});
(The code properly executes in the latest Firefox Nightly, but not in Chrome 47)
它在 chrome 47 和 Firefox Nightly 中不起作用的原因是 ES6 class
es 在 chrome 中还没有完全支持(它目前在功能标志下 chrome://flags/#enable-javascript-harmony
在 chrome 47)
关于javascript - ES6 Promise 和 Class 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34566095/