Last active
July 22, 2016 09:07
-
-
Save troygoode/cb82991c71eafa0c7323 to your computer and use it in GitHub Desktop.
Promise Cancellation Example
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
// to run: | |
// $ npm install bluebird | |
// $ node cancel-promise.js | |
// example from: http://openmymind.net/Cancelling-Long-Promise-Chains/ | |
(function () { | |
'use strict'; | |
var Promise = require('bluebird'); | |
function a(v) { | |
return Promise.resolve(v); | |
} | |
function b(v) { | |
return v * 2; | |
} | |
function c(v) { | |
return v * 2; | |
} | |
function chain(v) { | |
var p = a(v) | |
.then(function (value) { | |
console.log(value); | |
if (!value) { | |
return p.cancel(); | |
} | |
return b(value); | |
}) | |
.then(function (value) { | |
console.log(value); | |
return c(value); | |
}) | |
.cancellable() | |
.catch(Promise.CancellationError, function () { | |
console.log('cancelled!'); | |
return 0; | |
}); | |
return p; | |
} | |
Promise.resolve() | |
.then(function () { | |
console.log('--------------------------------------------------------------------------------'); | |
console.log('Chain [1]'); | |
console.log('--------------------------------------------------------------------------------'); | |
return chain(1) | |
.then(function (v) { | |
console.log('Chain [1]: %s', v); // will print 4 | |
}) | |
.catch(function (err) { | |
console.error('Chain [1] Error', err); // won't be called | |
}); | |
}) | |
.then(function () { | |
console.log('--------------------------------------------------------------------------------'); | |
console.log('Chain [undefined]'); | |
console.log('--------------------------------------------------------------------------------'); | |
return chain(undefined) // same as saying `return chain()`, but I'm being explicit for illustration purposes | |
.then(function (v) { | |
console.log('Chain [undefined]: %s', v); // will print 0 because of cancellation handler | |
}) | |
.catch(function (err) { | |
console.error('Chain [undefined] Error', err); // won't be called | |
}); | |
}); | |
}()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried
Response :