Skip to content

Instantly share code, notes, and snippets.

@nuxlli
Created November 22, 2012 17:01
Promise Q: Little trick for stop and return a value in a sequence
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);
})
// Print
// first value
// ended
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment