承诺没有发现错误

时间:2016-03-13 11:22:51

标签: javascript ajax promise addeventlistener

function getJSON(url){
    return new Promise(function(resolveFN, crashFN){
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'json';
        processing(); //this is for special notifcation appear
        request.onload = function(e){
            resolveFN(request.response);
            removeProcessing(); //this is for special notifcation disappear after 'onload'
        };

        request.onerror = function(){
            debugger; //this is not invoked when url is wrong
            crashFN(new Error(' Couldn\'t load at: ' + url));
        };

        request.send();
    });
}

接下来当我使用eventListener时 - 它没有发现错误:

var prev = document.getElementById('prev');

prev.addEventListener('click', function(){
    getJSON('http://marsweather.ingenology.com/v1/archive/1').then(function(response){
        debugger; //this is invoked
        console.log(response);
    }).catch(function(err){
        debugger; // and this is not invoked. why?
        console.log('errrrrrrer ', err);
    });
});

catch不能在eventListener内部工作的原因是什么?

更新:Dmitriy Loskutov建议这样做 - When should XMLHttpRequest's onerror handler fire

1 个答案:

答案 0 :(得分:0)

Promise没有错。您需要适当检查status处理程序中的onload

    request.onload = function(e){
        if (request.status === 200) {
            resolveFN(request.response);
        }
        else {
            rejectFN(...);
        }
        removeProcessing(); //this is for special notifcation disappear after 'onload'
    };