Created
November 22, 2012 17:01
Promise Q: Little trick for stop and return a value in a sequence
This file contains 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 S = new (function() { | |
var STOPPED = function(value) { | |
this.value = value | |
}; | |
this.return = function(value) { | |
throw new STOPPED(value) | |
} | |
this.stoppable = function(promise) { | |
return promise.fail(function(msg) { | |
if (msg instanceof STOPPED) { | |
return Q.resolve(msg.value); | |
} else { | |
return Q.reject(msg); | |
} | |
}) | |
} | |
}) | |
S.stoppable( | |
Q.resolve('first value') | |
.then(function(value) { | |
console.log(value) | |
S.return("ended"); | |
}) | |
.then(function() { | |
console.log('never here') | |
}) | |
) | |
.then(function(value) { | |
console.log(value) | |
}) | |
.fail(function(err) { | |
console.log("fail", err.stack); | |
}) | |
// first value | |
// ended |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment