Here's a more complete answer, returning to the caller isn't possible. Because Promise are running asynchrously... in other words, the caller already returned when the promise started working. So returning to the caller isn't possible because the caller is already gone.
If you want to leave the promise, you can simply call this.reject()
You can reject with a parameter. It will get caught in a catch
promise. You can reject
from a catch
clause too if you don't want it to process any more then
. Then at some point, this will result in the promise failing.
It might not do exactly what you want because you'll have to handle at least on final catch
to handle the errors or why you left early from the promise. But even the catch
is a promise.
outerFunction = ->
Q()
.then ->
doSomethingAsync
.then (result) ->
if error
this.reject(result)
return result if result is someSpecialValue
.then ->
...
.then ->
...
.catch (error) ->
console.log("Handling error", error)
Here's a bit more documentation on promises: http://promisejs.org/ This is a good read.
I hope you understand that using
reject is pretty much like trying to early exit from a function couple of stacked function by raising an exception. I do not encourage this as it could be quite terrible and hard to understand the logic behind it. If you have to early exit from a promise even though there is no exceptions or error, then you probably have to rethink about your flow.
What you could do is this instead:
outerFunction = ->
Q()
.then ->
doSomethingAsync
.then (result) ->
if return_now
return result if result is someSpecialValue
return Q()
.then ->
...
.then ->
...
.then ->
...
You could return your result or return a promise that will continue the process chain.