JS Q库 - 延迟错误捕获

时间:2014-02-27 09:54:41

标签: javascript promise deferred q

我发现了Kris Koval Q库,我遇到了问题。看看这个简单的代码:

function getPromise1() {
    var deferred = Q.defer();
    setTimeout(function () {
        console.log('Promise 1 OK');
        deferred.resolve();
    }, 1000);
    return deferred.promise;
}


function getPromise2() {
    var deferred = Q.defer();
    setTimeout(function () {
        console.log('Promise 2 Failed');
        deferred.reject();
    }, 1000);
    return deferred.promise;
}

getPromise1()
    .then(getPromise2())
    .fail(function () {
        alert('Fail!');
    })
    .done();

我希望看到:

Promise 1 OK
Promise 2 Failed

然后显示警告“失败!”,但警报从未显示。而不是我在控制台中看到警告:

[Q] Unhandled rejection reasons (should be empty): ["(no stack) undefined"] 

为什么不处理拒绝以及如何处理?

1 个答案:

答案 0 :(得分:1)

then函数中,您应该只传递getPromise2函数,而不是getPromise2()的结果

getPromise1()
    .then(getPromise2)            // NOTE: We are not calling it here
    .fail(function () {
        console.log('Fail!');
    })
    .done();