<head>
<title>Promises/A forwarding</title>
<script src="https://raw.github.com/cujojs/when/master/when.js"></script>
</head>
<body>
<div><p>This is a simple when.js example of how Promises/A forwarding works in promise resolutions and rejections.</p></div>
<hr>
</body>
JavaScript
// Examples of Promises/A forwarding.
// A few simple examples to show how the mechanics of Promises/A
// forwarding works.
// These examples are contrived, of course, and in real usage, promise
// chains will typically be spread across several function calls, or
// even several levels of your application architecture.
var d;
d = when.defer();
// Resolved promises chain and forward values to next promise
// The first promise, d.promise, will resolve with the value passed
// to d.resolve() below.
// Each call to .then() returns a new promise that will resolve
// with the return value of the previous handler. This creates a
// promise "pipeline".
d.promise
.then(function(x) {
// x will be the value passed to d.resolve() below
// and returns a *new promise* for x + 1
return x + 1;
})
.then(function(x) {
// x === 2
// This handler receives the return value of the
// previous handler.
return x + 1;
})
.then(function(x) {
// x === 3
// This handler receives the return value of the
// previous handler.
return x + 1;
})
.then(function(x) {
// x === 4
// This handler receives the return value of the
// previous handler.
log('resolve ' + x);
});
d.resolve(1);
// Rejected promises behave similarly, and also work similarly
// to try/catch:
// When you catch an exception, you must rethrow for it to propagate.
// Similarly, when you handle a rejected promise, to propagate the
// rejection, "rethrow" it by either returning a rejected promise,
// or actually throwing (since when.js translates thrown exceptions
// into rejections)
d = when.defer();
d.promise
.then(function(x) {
throw x + 1;
})
.then(null, function(x) {
// Propagate the rejection
throw x + 1;
})
.then(null, function(x) {
// Can also propagate by returning another rejection
return when.reject(x +...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.