JS Q library - defer error catching
-
23-12-2019 - |
Question
I'm discovering Kris Koval Q library and I have a problem. Look at this simple code:
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();
I expect to see:
Promise 1 OK
Promise 2 Failed
and then show alert "Fail!", but the alert never shows. Instead of that I see warning in my console:
[Q] Unhandled rejection reasons (should be empty): ["(no stack) undefined"]
Why rejection is not handled and how can I handle it?
Solution
In the then
function, you should pass just the getPromise2
function, not the result of getPromise2()
getPromise1()
.then(getPromise2) // NOTE: We are not calling it here
.fail(function () {
console.log('Fail!');
})
.done();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow