My promise question
I am new to Promises and I read Q Documentation that says:
When you get to the end of the promises chain, you must either return the last promise or end the chain.
I defined Promise in my Q.Promise code, with the following console.log , to exit the execution trace:
function foo(){ return Q.Promise(function(resolve, reject) { doSomething() .then(function() { console.log('1'); return doSomething1(); }) .then(function() { console.log('2'); return doSomething2(); }) .then(function() { console.log('3'); return doSomething3(); }) .catch(function(err) { console.log('catch!!'); reject(err); }) .done(function() { console.log('done!!'); resolve(); }); }); }
If each doSomethingN() runs correctly, everything works as intended, and I get the expected trace:
1 2 3 done!!
But if any of doSomethingN() :
foo() works correctly since the error function callback is the one that fires whenever the reject(err) event occurs:
foo().then(function() { /* */ }, function(err) { /* this runs! */ });
And I get the following trace (i.e. when doSomething1() does not work):
1 catch!! done!!
My question
At first, I thought the following:
Ok, let the chain handle success and failure in both methods: .done() and .catch() . If all goes well .done() will call back and the promise will be resolved. In the event of an error, a callback to .catch() will be executed at any point, and the promise will be rejected - and because of this, done() will not be executed.
I think I'm missing something about how .done() works ... because, looking at my logging trace, I realized that .done() seems to always execute - is there an error and .catch() is executed or not - and I did not expect this.
So after that I removed the .done() and now foo() :
- works if there is
error at run time - not working if everything is working correctly
What should I review and how do I / make it work?