Last active
August 29, 2015 14:22
-
-
Save ndruger/85ce43bd5650323e0e73 to your computer and use it in GitHub Desktop.
early return on Q
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var Q = require('q'); | |
| var util = require('util'); | |
| var fn = Q.makePromise.prototype; | |
| fn.catchForceReturn = catchForceReturn; | |
| function ForceReturn(value) { | |
| Error.call(this, value); | |
| this.name = "ForceReturn"; | |
| this.value = value; | |
| } | |
| util.inherits(ForceReturn, Error); | |
| Q.ForceReturn = ForceReturn; | |
| function catchForceReturn(fn) { | |
| return this | |
| .fail(function(e) { | |
| if (e instanceof ForceReturn) { | |
| return e.value; | |
| } else { | |
| throw e; | |
| } | |
| }) | |
| .then(fn); | |
| } | |
| module.exports = Q; | |
| /* Usage | |
| var Q = require('force-return-q'); | |
| function testQ() { | |
| return Q() | |
| .then(function() { | |
| throw new Q.ForceReturn('return value'); | |
| }) | |
| .then(function() { | |
| console.log('will be skipped'); | |
| }) | |
| .catchForceReturn() | |
| .fail(function(e) { | |
| console.log('fail', e && e.stack); | |
| return 'return fail value'; | |
| }); | |
| } | |
| testQ() | |
| .done(function(v) { | |
| console.log('done', v); | |
| }); | |
| */ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bluebird has .cancel
http://openmymind.net/Cancelling-Long-Promise-Chains/
kriskowal/q#64